Skip to content

Commit 4369957

Browse files
authored
Unwrap strict errors (#1012)
1 parent a0e8464 commit 4369957

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

errors.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,17 @@ func (s *StrictMissingError) String() string {
5454
return buf.String()
5555
}
5656

57+
// Unwrap returns wrapped decode errors
58+
//
59+
// Implements errors.Join() interface.
60+
func (s *StrictMissingError) Unwrap() []error {
61+
var errs []error
62+
for i := range s.Errors {
63+
errs = append(errs, &s.Errors[i])
64+
}
65+
return errs
66+
}
67+
5768
type Key []string
5869

5970
// Error returns the error message contained in the DecodeError.
@@ -78,7 +89,7 @@ func (e *DecodeError) Key() Key {
7889
return e.key
7990
}
8091

81-
// decodeErrorFromHighlight creates a DecodeError referencing a highlighted
92+
// wrapDecodeError creates a DecodeError referencing a highlighted
8293
// range of bytes from document.
8394
//
8495
// highlight needs to be a sub-slice of document, or this function panics.

errors_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,21 @@ func TestDecodeError_Accessors(t *testing.T) {
205205
assert.Equal(t, "bar", e.String())
206206
}
207207

208+
func TestStrictErrorUnwrap(t *testing.T) {
209+
fo := bytes.NewBufferString(`
210+
Missing = 1
211+
OtherMissing = 1
212+
`)
213+
var out struct{}
214+
err := NewDecoder(fo).DisallowUnknownFields().Decode(&out)
215+
assert.Error(t, err)
216+
217+
strictErr := &StrictMissingError{}
218+
assert.True(t, errors.As(err, &strictErr))
219+
220+
assert.Equal(t, 2, len(strictErr.Unwrap()))
221+
}
222+
208223
func ExampleDecodeError() {
209224
doc := `name = 123__456`
210225

0 commit comments

Comments
 (0)