Skip to content

Commit a8f3252

Browse files
Add Errors.Unwrap method (#24)
* Add Errors.Unwrap method This allows us to use errors.Is with errors returned from a failed validation. * Remove errors.Is test This only works from go1.20 onwards. And this project targets 1.13
1 parent 5a8c7c5 commit a8f3252

File tree

2 files changed

+24
-0
lines changed

2 files changed

+24
-0
lines changed

error.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,17 @@ func (es Errors) Error() string {
141141
return s.String()
142142
}
143143

144+
// Unwrap returns a slice of the non-nil errors in the Errors.
145+
func (es Errors) Unwrap() []error {
146+
errs := make([]error, 0, len(es))
147+
for _, err := range es {
148+
if err != nil {
149+
errs = append(errs, err)
150+
}
151+
}
152+
return errs
153+
}
154+
144155
// MarshalJSON converts the Errors into a valid JSON.
145156
func (es Errors) MarshalJSON() ([]byte, error) {
146157
errs := map[string]interface{}{}

error_test.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,19 @@ func TestErrors_Filter(t *testing.T) {
7070
assert.Nil(t, errs.Filter())
7171
}
7272

73+
func TestErrors_Unwrap(t *testing.T) {
74+
errs := Errors{
75+
"B": errors.New("B1"),
76+
"C": nil,
77+
"A": errors.New("A1"),
78+
}
79+
80+
unwrapped := errs.Unwrap()
81+
assert.Contains(t, unwrapped, errs["B"])
82+
assert.Contains(t, unwrapped, errs["A"])
83+
assert.Len(t, unwrapped, 2)
84+
}
85+
7386
func TestErrorObject_SetCode(t *testing.T) {
7487
err := NewError("A", "msg").(ErrorObject)
7588

0 commit comments

Comments
 (0)