diff --git a/error.go b/error.go index e75b1de..fa0e2e2 100644 --- a/error.go +++ b/error.go @@ -141,6 +141,17 @@ func (es Errors) Error() string { return s.String() } +// Unwrap returns a slice of the non-nil errors in the Errors. +func (es Errors) Unwrap() []error { + errs := make([]error, 0, len(es)) + for _, err := range es { + if err != nil { + errs = append(errs, err) + } + } + return errs +} + // MarshalJSON converts the Errors into a valid JSON. func (es Errors) MarshalJSON() ([]byte, error) { errs := map[string]interface{}{} diff --git a/error_test.go b/error_test.go index e0985c5..91eb5d5 100644 --- a/error_test.go +++ b/error_test.go @@ -70,6 +70,19 @@ func TestErrors_Filter(t *testing.T) { assert.Nil(t, errs.Filter()) } +func TestErrors_Unwrap(t *testing.T) { + errs := Errors{ + "B": errors.New("B1"), + "C": nil, + "A": errors.New("A1"), + } + + unwrapped := errs.Unwrap() + assert.Contains(t, unwrapped, errs["B"]) + assert.Contains(t, unwrapped, errs["A"]) + assert.Len(t, unwrapped, 2) +} + func TestErrorObject_SetCode(t *testing.T) { err := NewError("A", "msg").(ErrorObject)