errors.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package jsonutils
  2. import (
  3. "fmt"
  4. "yunion.io/x/pkg/errors"
  5. )
  6. const (
  7. ErrJsonDictFailInsert = errors.Error("fail to insert object")
  8. ErrInvalidJsonDict = errors.Error("not a valid JSONDict")
  9. ErrInvalidJsonArray = errors.Error("not a valid JSONArray")
  10. ErrInvalidJsonInt = errors.Error("not a valid number")
  11. ErrInvalidJsonFloat = errors.Error("not a valid float")
  12. ErrInvalidJsonBoolean = errors.Error("not a valid boolean")
  13. ErrInvalidJsonString = errors.Error("not a valid string")
  14. ErrJsonDictKeyNotFound = errors.Error("key not found")
  15. ErrUnsupported = errors.Error("unsupported operation")
  16. ErrOutOfKeyRange = errors.Error("out of key range")
  17. ErrOutOfIndexRange = errors.Error("out of index range")
  18. ErrInvalidChar = errors.Error("invalid char")
  19. ErrInvalidHex = errors.Error("invalid hex")
  20. ErrInvalidRune = errors.Error("invalid 4 byte rune")
  21. ErrTypeMismatch = errors.Error("unmarshal type mismatch")
  22. ErrArrayLengthMismatch = errors.Error("unmarshal array length mismatch")
  23. ErrInterfaceUnsupported = errors.Error("do not known how to deserialize json into this interface type")
  24. ErrMapKeyMustString = errors.Error("map key must be string")
  25. ErrMissingInputField = errors.Error("missing input field")
  26. ErrNilInputField = errors.Error("nil input field")
  27. ErrYamlMissingDictKey = errors.Error("Cannot find JSONDict key")
  28. ErrYamlIllFormat = errors.Error("Illformat")
  29. )
  30. type JSONError struct {
  31. pos int
  32. substr string
  33. msg string
  34. }
  35. func (e *JSONError) Error() string {
  36. return fmt.Sprintf("JSON error %s at %d: %s...", e.msg, e.pos, e.substr)
  37. }
  38. func NewJSONError(str []byte, pos int, msg string) *JSONError {
  39. if len(str) == 0 {
  40. return &JSONError{pos: 0, substr: "", msg: msg}
  41. }
  42. if pos < 0 {
  43. pos = 0
  44. } else if pos > len(str)-1 {
  45. pos = len(str) - 1
  46. }
  47. sublen := 10
  48. start := pos - sublen
  49. end := pos + sublen
  50. if start < 0 {
  51. start = 0
  52. }
  53. if end > len(str) {
  54. end = len(str)
  55. }
  56. substr := make([]byte, end-start+1)
  57. copy(substr, str[start:pos])
  58. substr[pos-start] = '^'
  59. copy(substr[pos-start+1:], str[pos:end])
  60. return &JSONError{pos: pos, substr: string(substr), msg: msg}
  61. }