github.com/docker/compose-on-kubernetes@v0.5.0/internal/error-group.go (about) 1 package internal 2 3 import ( 4 "fmt" 5 ) 6 7 // ErrorGroup is a type of error that aggregates several errors. 8 type ErrorGroup struct { 9 errors []error 10 } 11 12 func (err ErrorGroup) Error() string { 13 res := "multiple errors: " 14 for i, e := range err.errors { 15 if i != 0 { 16 res += ", " 17 } 18 res += fmt.Sprintf("%q", e) 19 } 20 return res 21 } 22 23 // GroupErrors returns an aggregation of several errors applying 24 // simplifications: ignore nils, avoid groups of one, flatten 25 // subgroups of errors, etc. 26 func GroupErrors(errs ...error) error { 27 // Collect all (sub) errors. 28 errors := []error{} 29 for _, e := range errs { 30 if e == nil { 31 continue 32 } 33 if g, ok := e.(ErrorGroup); ok { 34 errors = append(errors, g.errors...) 35 } else { 36 errors = append(errors, e) 37 } 38 } 39 switch len(errors) { 40 case 0: 41 return nil 42 case 1: 43 return errors[0] 44 default: 45 return ErrorGroup{errors} 46 } 47 }