From 0023bb0ab1225a10509dca08627b42bed25d74a5 Mon Sep 17 00:00:00 2001 From: Seth Vargo Date: Thu, 11 Mar 2021 15:06:12 -0500 Subject: [PATCH] Check if multierror is nil in WrappedErrors 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. --- multierror.go | 15 +++++++++------ multierror_test.go | 5 +++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/multierror.go b/multierror.go index d05dd92..f545743 100644 --- a/multierror.go +++ b/multierror.go @@ -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 } diff --git a/multierror_test.go b/multierror_test.go index 972c52d..ed1f08c 100644 --- a/multierror_test.go +++ b/multierror_test.go @@ -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) {