errors.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. // Copyright 2020 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package jsontext
  5. import (
  6. "bytes"
  7. "io"
  8. "strconv"
  9. "github.com/go-json-experiment/json/internal/jsonwire"
  10. )
  11. const errorPrefix = "jsontext: "
  12. type ioError struct {
  13. action string // either "read" or "write"
  14. err error
  15. }
  16. func (e *ioError) Error() string {
  17. return errorPrefix + e.action + " error: " + e.err.Error()
  18. }
  19. func (e *ioError) Unwrap() error {
  20. return e.err
  21. }
  22. // SyntacticError is a description of a syntactic error that occurred when
  23. // encoding or decoding JSON according to the grammar.
  24. //
  25. // The contents of this error as produced by this package may change over time.
  26. type SyntacticError struct {
  27. requireKeyedLiterals
  28. nonComparable
  29. // ByteOffset indicates that an error occurred after this byte offset.
  30. ByteOffset int64
  31. // JSONPointer indicates that an error occurred within this JSON value
  32. // as indicated using the JSON Pointer notation (see RFC 6901).
  33. JSONPointer Pointer
  34. // Err is the underlying error.
  35. Err error
  36. }
  37. // wrapSyntacticError wraps an error and annotates it with a precise location
  38. // using the provided [encoderState] or [decoderState].
  39. // If err is an [ioError] or [io.EOF], then it is not wrapped.
  40. //
  41. // It takes a relative offset pos that can be resolved into
  42. // an absolute offset using state.offsetAt.
  43. //
  44. // It takes a where that specify how the JSON pointer is derived.
  45. // If the underlying error is a [pointerSuffixError],
  46. // then the suffix is appended to the derived pointer.
  47. func wrapSyntacticError(state interface {
  48. offsetAt(pos int) int64
  49. AppendStackPointer(b []byte, where int) []byte
  50. }, err error, pos, where int) error {
  51. if _, ok := err.(*ioError); err == io.EOF || ok {
  52. return err
  53. }
  54. offset := state.offsetAt(pos)
  55. ptr := state.AppendStackPointer(nil, where)
  56. if serr, ok := err.(*pointerSuffixError); ok {
  57. ptr = serr.appendPointer(ptr)
  58. err = serr.error
  59. }
  60. if d, ok := state.(*decoderState); ok && err == errMismatchDelim {
  61. where := "at start of value"
  62. if len(d.Tokens.Stack) > 0 && d.Tokens.Last.Length() > 0 {
  63. switch {
  64. case d.Tokens.Last.isArray():
  65. where = "after array element (expecting ',' or ']')"
  66. ptr = []byte(Pointer(ptr).Parent()) // problem is with parent array
  67. case d.Tokens.Last.isObject():
  68. where = "after object value (expecting ',' or '}')"
  69. ptr = []byte(Pointer(ptr).Parent()) // problem is with parent object
  70. }
  71. }
  72. err = jsonwire.NewInvalidCharacterError(d.buf[pos:], where)
  73. }
  74. return &SyntacticError{ByteOffset: offset, JSONPointer: Pointer(ptr), Err: err}
  75. }
  76. func (e *SyntacticError) Error() string {
  77. pointer := e.JSONPointer
  78. offset := e.ByteOffset
  79. b := []byte(errorPrefix)
  80. if e.Err != nil {
  81. b = append(b, e.Err.Error()...)
  82. if e.Err == ErrDuplicateName {
  83. b = strconv.AppendQuote(append(b, ' '), pointer.LastToken())
  84. pointer = pointer.Parent()
  85. offset = 0 // not useful to print offset for duplicate names
  86. }
  87. } else {
  88. b = append(b, "syntactic error"...)
  89. }
  90. if pointer != "" {
  91. b = strconv.AppendQuote(append(b, " within "...), jsonwire.TruncatePointer(string(pointer), 100))
  92. }
  93. if offset > 0 {
  94. b = strconv.AppendInt(append(b, " after offset "...), offset, 10)
  95. }
  96. return string(b)
  97. }
  98. func (e *SyntacticError) Unwrap() error {
  99. return e.Err
  100. }
  101. // pointerSuffixError represents a JSON pointer suffix to be appended
  102. // to [SyntacticError.JSONPointer]. It is an internal error type
  103. // used within this package and does not appear in the public API.
  104. //
  105. // This type is primarily used to annotate errors in Encoder.WriteValue
  106. // and Decoder.ReadValue with precise positions.
  107. // At the time WriteValue or ReadValue is called, a JSON pointer to the
  108. // upcoming value can be constructed using the Encoder/Decoder state.
  109. // However, tracking pointers within values during normal operation
  110. // would incur a performance penalty in the error-free case.
  111. //
  112. // To provide precise error locations without this overhead,
  113. // the error is wrapped with object names or array indices
  114. // as the call stack is popped when an error occurs.
  115. // Since this happens in reverse order, pointerSuffixError holds
  116. // the pointer in reverse and is only later reversed when appending to
  117. // the pointer prefix.
  118. //
  119. // For example, if the encoder is at "/alpha/bravo/charlie"
  120. // and an error occurs in WriteValue at "/xray/yankee/zulu", then
  121. // the final pointer should be "/alpha/bravo/charlie/xray/yankee/zulu".
  122. //
  123. // As pointerSuffixError is populated during the error return path,
  124. // it first contains "/zulu", then "/zulu/yankee",
  125. // and finally "/zulu/yankee/xray".
  126. // These tokens are reversed and concatenated to "/alpha/bravo/charlie"
  127. // to form the full pointer.
  128. type pointerSuffixError struct {
  129. error
  130. // reversePointer is a JSON pointer, but with each token in reverse order.
  131. reversePointer []byte
  132. }
  133. // wrapWithObjectName wraps err with a JSON object name access,
  134. // which must be a valid quoted JSON string.
  135. func wrapWithObjectName(err error, quotedName []byte) error {
  136. serr, _ := err.(*pointerSuffixError)
  137. if serr == nil {
  138. serr = &pointerSuffixError{error: err}
  139. }
  140. name := jsonwire.UnquoteMayCopy(quotedName, false)
  141. serr.reversePointer = appendEscapePointerName(append(serr.reversePointer, '/'), name)
  142. return serr
  143. }
  144. // wrapWithArrayIndex wraps err with a JSON array index access.
  145. func wrapWithArrayIndex(err error, index int64) error {
  146. serr, _ := err.(*pointerSuffixError)
  147. if serr == nil {
  148. serr = &pointerSuffixError{error: err}
  149. }
  150. serr.reversePointer = strconv.AppendUint(append(serr.reversePointer, '/'), uint64(index), 10)
  151. return serr
  152. }
  153. // appendPointer appends the path encoded in e to the end of pointer.
  154. func (e *pointerSuffixError) appendPointer(pointer []byte) []byte {
  155. // Copy each token in reversePointer to the end of pointer in reverse order.
  156. // Double reversal means that the appended suffix is now in forward order.
  157. bi, bo := e.reversePointer, pointer
  158. for len(bi) > 0 {
  159. i := bytes.LastIndexByte(bi, '/')
  160. bi, bo = bi[:i], append(bo, bi[i:]...)
  161. }
  162. return bo
  163. }