mirror of
https://github.com/k3s-io/kubernetes.git
synced 2025-08-01 07:47:56 +00:00
fix errors.NewAggregate nil pointer panic
Change-Id: I82b376898f9170d237a3bd1a1ac898cc6c636d12
This commit is contained in:
parent
c9fda51d77
commit
90bf34cafd
@ -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
|
||||
|
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user