Skip to content

Commit

Permalink
ErrorWrap: embed the error
Browse files Browse the repository at this point in the history
Provide a constructor NewErrorWrap
  • Loading branch information
Greg Weber committed Oct 31, 2024
1 parent 6c5ddfc commit 137a0d0
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 6 deletions.
11 changes: 6 additions & 5 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -401,20 +401,21 @@ func WrapInPlace(err error, wrap func(error) error) bool {
// If fulfills the WrapError interface.
// This allows for wrapping an inner error without changing the outer type.
type ErrorWrap struct {
Err error
error
}

func (ew *ErrorWrap) Error() string {
return ew.Err.Error()
// NewErrorWrap returns a pointer because ErrorWrap should be used as a pointer.
func NewErrorWrap(err error) *ErrorWrap {
return &ErrorWrap{err}
}

// This struct is designed to be used as an embeded error.
func (ew *ErrorWrap) Unwrap() error {
return ew.Err
return ew.error
}

func (ew *ErrorWrap) WrapError(wrap func(error) error) {
ew.Err = wrap(ew.Err)
ew.error = wrap(ew.error)
}

var _ ErrorWrapper = (*ErrorWrap)(nil) // assert implements interface
Expand Down
2 changes: 1 addition & 1 deletion errors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -424,7 +424,7 @@ type WrappedInPlace struct {
}

func TestErrorWrapper(t *testing.T) {
err := WrappedInPlace{&ErrorWrap{Err: New("underlying")}}
err := WrappedInPlace{&ErrorWrap{New("underlying")}}
if err.Error() != "underlying" {
t.Errorf("Error()")
}
Expand Down

0 comments on commit 137a0d0

Please sign in to comment.