Debian Codegraph @

internal/libyaml/errors.go

raw symbols SCIP
1 // Copyright 2025 The go-yaml Project Contributors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Error types for YAML parsing and emitting.
5 // Provides structured error reporting with line/column information.
6
7 package libyaml
8
9 import (
10 "errors"
11 "fmt"
12 "strings"
13 )
14
15 // Stage identifies the processing stage where an error occurred during YAML
16 // loading or dumping.
17 type Stage string
18
19 const (
20 // Load stages
21 ReaderStage Stage = "reader" // Input reading and encoding
22 ScannerStage Stage = "scanner" // Tokenization
23 ParserStage Stage = "parser" // Event stream parsing
24 ComposerStage Stage = "composer" // Node tree construction
25 ResolverStage Stage = "resolver" // Tag resolution
26 ConstructorStage Stage = "constructor" // Go value construction
27
28 // Dump stages
29 RepresenterStage Stage = "representer" // Go value to Node tree
30 SerializerStage Stage = "serializer" // Node tree to events
31 EmitterStage Stage = "emitter" // Events to YAML bytes
32 WriterStage Stage = "writer" // Output writing
33 )
34
35 // LoadError represents an error that occurred while loading a YAML document.
36 //
37 // It provides detailed location information and identifies the processing
38 // stage where the error occurred.
39 type LoadError struct {
40 Stage Stage // Processing stage where error occurred
41 Message string // Error description
42
43 // Position information
44 Mark Mark // Primary error position
45 ContextMark Mark // Optional context position (e.g., start of construct)
46 ContextMsg string // Optional context message
47
48 // Error chaining
49 err error // Underlying error (for Unwrap support)
50 }
51
52 // Error returns the error message with stage and position information.
53 // Format: "go-yaml load error in <stage> at L:C: <message>"
54 // Or with context: "go-yaml load error in <stage> (<ctx>) at L:C-L:C: <message>"
55 func (e *LoadError) Error() string {
56 if len(e.ContextMsg) > 0 {
57 return fmt.Sprintf("go-yaml load error in %s (%s) at %s: %s",
58 e.Stage, e.ContextMsg, e.ContextMark.rangeString(e.Mark), e.Message)
59 }
60 return fmt.Sprintf("go-yaml load error in %s at %s: %s",
61 e.Stage, e.Mark.shortString(), e.Message)
62 }
63
64 // simpleError returns the error message without the "yaml: Load error (in stage)" prefix.
65 // Used for formatting errors within LoadErrors collections.
66 // Format: "line L: <message>" (backwards compatible - no column info)
67 func (e *LoadError) simpleError() string {
68 var builder strings.Builder
69 if len(e.ContextMsg) > 0 {
70 fmt.Fprintf(&builder, "%s at %s: ", e.ContextMsg, e.ContextMark)
71 }
72 if len(e.ContextMsg) == 0 || e.ContextMark != e.Mark {
73 if e.Mark.Line > 0 {
74 fmt.Fprintf(&builder, "line %d: ", e.Mark.Line)
75 } else {
76 builder.WriteString("<unknown position>: ")
77 }
78 }
79 builder.WriteString(e.Message)
80 return builder.String()
81 }
82
83 // Unwrap returns the underlying error.
84 func (e *LoadError) Unwrap() error {
85 return e.err
86 }
87
88 // NewLoadError creates a LoadError with an underlying cause.
89 // The cause is accessible via Unwrap for use with [errors.Is] and [errors.As].
90 func NewLoadError(stage Stage, message string, mark Mark, cause error) *LoadError {
91 return &LoadError{
92 Stage: stage,
93 Message: message,
94 Mark: mark,
95 err: cause,
96 }
97 }
98
99 // DumpError represents an error that occurred while dumping a YAML document.
100 //
101 // It identifies the processing stage where the error occurred and provides
102 // an optional underlying cause via Unwrap.
103 type DumpError struct {
104 Stage Stage // Processing stage where error occurred
105 Message string // Error description
106
107 // Error chaining
108 err error // Underlying error (for Unwrap support)
109 }
110
111 // Error returns the error message with stage information.
112 // Format: "go-yaml dump error in <stage>: <message>"
113 func (e *DumpError) Error() string {
114 return fmt.Sprintf("go-yaml dump error in %s: %s", e.Stage, e.Message)
115 }
116
117 // Unwrap returns the underlying error.
118 func (e *DumpError) Unwrap() error {
119 return e.err
120 }
121
122 // NewDumpError creates a DumpError with an underlying cause.
123 // The cause is accessible via Unwrap for use with [errors.Is] and [errors.As].
124 func NewDumpError(stage Stage, message string, cause error) *DumpError {
125 return &DumpError{Stage: stage, Message: message, err: cause}
126 }
127
128 // failDump panics with a YAMLError wrapping a DumpError for the given stage.
129 // If err is exactly a *DumpError it is passed through unchanged to avoid
130 // double-wrapping (e.g. a user MarshalYAML that returns yaml.NewDumpError).
131 // Errors that merely wrap a *DumpError are treated as ordinary errors so that
132 // the outer wrapper's message and context are preserved.
133 func failDump(stage Stage, err error) {
134 if de, ok := err.(*DumpError); ok {
135 panic(&YAMLError{de})
136 }
137 panic(&YAMLError{&DumpError{Stage: stage, Message: err.Error(), err: err}})
138 }
139
140 // failDumpf panics with a YAMLError wrapping a formatted DumpError.
141 func failDumpf(stage Stage, format string, args ...any) {
142 panic(&YAMLError{&DumpError{Stage: stage, Message: fmt.Sprintf(format, args...)}})
143 }
144
145 // EmitterError represents an error that occurred during emitting.
146 type EmitterError struct {
147 Message string
148 }
149
150 // Error returns the error message.
151 func (e EmitterError) Error() string {
152 return fmt.Sprintf("yaml: %s", e.Message)
153 }
154
155 // WriterError represents an error that occurred while writing output.
156 type WriterError struct {
157 Err error
158 }
159
160 // Error returns the error message.
161 func (e WriterError) Error() string {
162 return fmt.Sprintf("yaml: %s", e.Err)
163 }
164
165 // Unwrap returns the underlying error.
166 func (e WriterError) Unwrap() error {
167 return e.Err
168 }
169
170 // LoadErrors is returned when one or more fields cannot be properly decoded.
171 type LoadErrors struct {
172 Errors []*LoadError
173 }
174
175 // Error returns a formatted error message listing all construct errors.
176 func (e *LoadErrors) Error() string {
177 var b strings.Builder
178 b.WriteString("yaml: construct errors: ")
179 for i, err := range e.Errors {
180 if i > 0 {
181 b.WriteString("; ")
182 }
183 b.WriteString(err.simpleError())
184 }
185 return b.String()
186 }
187
188 // As implements [errors.As] for Go versions prior to 1.20 that don't support
189 // the Unwrap() []error interface. It allows [LoadErrors] to match against
190 // *LoadError or *TypeError targets.
191 func (e *LoadErrors) As(target any) bool {
192 switch t := target.(type) {
193 case **LoadError:
194 if len(e.Errors) == 0 {
195 return false
196 }
197 *t = e.Errors[0]
198 return true
199 case **TypeError:
200 var msgs []string
201 for _, err := range e.Errors {
202 msgs = append(msgs, err.simpleError())
203 }
204 *t = &TypeError{Errors: msgs}
205 return true
206 }
207 return false
208 }
209
210 // Is implements [errors.Is] for Go versions prior to 1.20 that don't support
211 // the Unwrap() []error interface. It checks if any wrapped error matches
212 // the target error.
213 func (e *LoadErrors) Is(target error) bool {
214 for _, err := range e.Errors {
215 if errors.Is(err, target) {
216 return true
217 }
218 }
219 return false
220 }
221
222 // TypeError is a legacy error type retained for compatibility.
223 //
224 // A TypeError is returned by Unmarshal when one or more fields in
225 // the YAML document cannot be properly decoded into the requested
226 // types. When this error is returned, the value is still
227 // unmarshaled partially.
228 //
229 // Deprecated: Use [LoadErrors] instead.
230 type TypeError struct {
231 Errors []string
232 }
233
234 // Error returns a formatted error message listing all unmarshal errors.
235 func (e *TypeError) Error() string {
236 return fmt.Sprintf("yaml: unmarshal errors: %s", strings.Join(e.Errors, "; "))
237 }
238
239 // YAMLError is an internal error wrapper type.
240 type YAMLError struct {
241 Err error
242 }
243
244 // Error returns the error message.
245 func (e *YAMLError) Error() string {
246 return e.Err.Error()
247 }
248
249 // handleErr recovers from panics caused by yaml errors.
250 // It's used in defer statements to convert YAMLError panics into regular errors.
251 func handleErr(err *error) {
252 if v := recover(); v != nil {
253 if e, ok := v.(*YAMLError); ok {
254 *err = e.Err
255 } else {
256 panic(v)
257 }
258 }
259 }