Skip to content

Commit

Permalink
Check if multierror is nil in WrappedErrors
Browse files Browse the repository at this point in the history
This adds a check similar to `ErrorsOrNil` that ensures the multierror pointer is not nil before returning the Errors field. I believe this is fully backwards-compatible, because the former behavior is a runtime panic.
  • Loading branch information
sethvargo committed Mar 11, 2021
1 parent ab6846a commit 0023bb0
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
15 changes: 9 additions & 6 deletions multierror.go
Expand Up @@ -40,14 +40,17 @@ func (e *Error) GoString() string {
return fmt.Sprintf("*%#v", *e)
}

// WrappedErrors returns the list of errors that this Error is wrapping.
// It is an implementation of the errwrap.Wrapper interface so that
// multierror.Error can be used with that library.
// WrappedErrors returns the list of errors that this Error is wrapping. It is
// an implementation of the errwrap.Wrapper interface so that multierror.Error
// can be used with that library.
//
// This method is not safe to be called concurrently and is no different
// than accessing the Errors field directly. It is implemented only to
// satisfy the errwrap.Wrapper interface.
// This method is not safe to be called concurrently. Unlike accessing the
// Errors field directly, this function also checks if the multierror is nil to
// prevent a null-pointer panic. It satisfies the errwrap.Wrapper interface.
func (e *Error) WrappedErrors() []error {
if e == nil {
return nil
}
return e.Errors
}

Expand Down
5 changes: 5 additions & 0 deletions multierror_test.go
Expand Up @@ -69,6 +69,11 @@ func TestErrorWrappedErrors(t *testing.T) {
if !reflect.DeepEqual(multi.Errors, multi.WrappedErrors()) {
t.Fatalf("bad: %s", multi.WrappedErrors())
}

multi = nil
if err := multi.WrappedErrors(); err != nil {
t.Fatalf("bad: %#v", multi)
}
}

func TestErrorUnwrap(t *testing.T) {
Expand Down

0 comments on commit 0023bb0

Please sign in to comment.