diff --git a/pkg/util/errors/errors.go b/pkg/util/errors/errors.go index 0445c142bea..42631f21622 100644 --- a/pkg/util/errors/errors.go +++ b/pkg/util/errors/errors.go @@ -31,11 +31,23 @@ type Aggregate interface { // NewAggregate converts a slice of errors into an Aggregate interface, which // is itself an implementation of the error interface. If the slice is empty, // this returns nil. +// It will check if any of the element of input error list is nil, to avoid +// nil pointer panic when call Error(). func NewAggregate(errlist []error) Aggregate { if len(errlist) == 0 { return nil } - return aggregate(errlist) + // In case of input error list contains nil + var errs []error + for _, e := range errlist { + if e != nil { + errs = append(errs, e) + } + } + if len(errs) == 0 { + return nil + } + return aggregate(errs) } // This helper implements the error and Errors interfaces. Keeping it private diff --git a/pkg/util/errors/errors_test.go b/pkg/util/errors/errors_test.go index 6698651c498..f453e570e8b 100644 --- a/pkg/util/errors/errors_test.go +++ b/pkg/util/errors/errors_test.go @@ -50,6 +50,46 @@ func TestEmptyAggregate(t *testing.T) { } } +func TestAggregateWithNil(t *testing.T) { + var slice []error + slice = []error{nil} + var agg Aggregate + var err error + + agg = NewAggregate(slice) + if agg != nil { + t.Errorf("expected nil, got %#v", agg) + } + err = NewAggregate(slice) + if err != nil { + t.Errorf("expected nil, got %#v", err) + } + + // Append a non-nil error + slice = append(slice, fmt.Errorf("err")) + agg = NewAggregate(slice) + if agg == nil { + t.Errorf("expected non-nil") + } + if s := agg.Error(); s != "err" { + t.Errorf("expected 'err', got %q", s) + } + if s := agg.Errors(); len(s) != 1 { + t.Errorf("expected one-element slice, got %#v", s) + } + if s := agg.Errors()[0].Error(); s != "err" { + t.Errorf("expected 'err', got %q", s) + } + + err = agg.(error) + if err == nil { + t.Errorf("expected non-nil") + } + if s := err.Error(); s != "err" { + t.Errorf("expected 'err', got %q", s) + } +} + func TestSingularAggregate(t *testing.T) { var slice []error = []error{fmt.Errorf("err")} var agg Aggregate