Skip to content

Commit 7761637

Browse files
committed
feat(errors): add ErrorOr for default
1 parent 2252d6f commit 7761637

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

go/errors/decorator.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,14 @@ func (hds HandlerDecorators) WrapHandler(next HandlerFunc) HandlerFunc {
4444
func (hds HandlerDecorators) WrapError(err error) error {
4545
return hds.WrapHandler(func(err error) error { return err })(err)
4646
}
47+
48+
// ErrorOr applies all decorators in the slice, in reverse order, to the error.
49+
// If the error is not handled, returns the default error.
50+
func (hds HandlerDecorators) ErrorOr(err error, defaultErr error) error {
51+
return hds.WrapHandler(func(err error) error {
52+
if err == nil {
53+
return nil
54+
}
55+
return defaultErr
56+
})(err)
57+
}

go/errors/decorator_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,3 +169,14 @@ func TestHandlerDecorators_WrapError(t *testing.T) {
169169
t.Errorf("Wrapped error does not contain the original error.")
170170
}
171171
}
172+
173+
func TestHandlerDecorators_ErrorOr(t *testing.T) {
174+
originalErr := errors.New("test error")
175+
176+
decorators := errors_.HandlerDecorators{}
177+
resultErr := decorators.ErrorOr(originalErr, errors.New("default error"))
178+
expectedErr := "default error"
179+
if resultErr.Error() != expectedErr {
180+
t.Errorf("Expected error '%s', but got '%s'", expectedErr, resultErr.Error())
181+
}
182+
}

0 commit comments

Comments
 (0)