forked from u-root/u-root
/
multierror.go
52 lines (48 loc) · 1.07 KB
/
multierror.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package util
import "bytes"
// MultiError pack multiple errors into one error.
type MultiError struct {
Errors []error
}
func (es MultiError) Error() string {
switch len(es.Errors) {
case 0:
return "no error"
case 1:
return es.Errors[0].Error()
default:
var buf bytes.Buffer
buf.WriteString("multiple errors: ")
for i, e := range es.Errors {
if i > 0 {
buf.WriteString("; ")
}
buf.WriteString(e.Error())
}
return buf.String()
}
}
// Errors concatenate multiple errors into one. If all errors are nil, it
// returns nil. If there is one non-nil error, it is returned. Otherwise the
// return value is a MultiError containing all the non-nil arguments. Arguments
// of the type MultiError are flattened.
func Errors(errs ...error) error {
var nonNil []error
for _, err := range errs {
if err != nil {
if multi, ok := err.(MultiError); ok {
nonNil = append(nonNil, multi.Errors...)
} else {
nonNil = append(nonNil, err)
}
}
}
switch len(nonNil) {
case 0:
return nil
case 1:
return nonNil[0]
default:
return MultiError{nonNil}
}
}