diff --git a/errors.go b/errors.go index 309733f1..e910a5ce 100644 --- a/errors.go +++ b/errors.go @@ -54,6 +54,17 @@ func (s *StrictMissingError) String() string { return buf.String() } +// Unwrap returns wrapped decode errors +// +// Implements errors.Join() interface. +func (s *StrictMissingError) Unwrap() []error { + var errs []error + for i := range s.Errors { + errs = append(errs, &s.Errors[i]) + } + return errs +} + type Key []string // Error returns the error message contained in the DecodeError. @@ -78,7 +89,7 @@ func (e *DecodeError) Key() Key { return e.key } -// decodeErrorFromHighlight creates a DecodeError referencing a highlighted +// wrapDecodeError creates a DecodeError referencing a highlighted // range of bytes from document. // // highlight needs to be a sub-slice of document, or this function panics. diff --git a/errors_test.go b/errors_test.go index 7b5ce64c..5b4e8c40 100644 --- a/errors_test.go +++ b/errors_test.go @@ -205,6 +205,21 @@ func TestDecodeError_Accessors(t *testing.T) { assert.Equal(t, "bar", e.String()) } +func TestStrictErrorUnwrap(t *testing.T) { + fo := bytes.NewBufferString(` +Missing = 1 +OtherMissing = 1 +`) + var out struct{} + err := NewDecoder(fo).DisallowUnknownFields().Decode(&out) + assert.Error(t, err) + + strictErr := &StrictMissingError{} + assert.True(t, errors.As(err, &strictErr)) + + assert.Equal(t, 2, len(strictErr.Unwrap())) +} + func ExampleDecodeError() { doc := `name = 123__456`