-
Notifications
You must be signed in to change notification settings - Fork 42
/
multierror.go
86 lines (77 loc) · 2.01 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package multierror
import (
"errors"
"strings"
)
type MultiError []error
// New creates a MultiError from a list of errors.
//
// This is just a convenience wrapper to ensure that if there is no error,
// if errs has len() == 0, or all errors are nil, nil is returned.
//
// In facts, you could normally convert a []error{} into a MultiError by simply
// using a cast: MultiError(errs). However, a simple cast would lead to a non
// nil error when errs has lenght 0.
func New(errs []error) error {
if len(errs) == 0 {
return nil
}
for _, err := range errs {
if err != nil {
return MultiError(errs)
}
}
return nil
}
// NewOr creates a MultiError from a list of errors, or returns the fallback error.
//
// Just like New, but gurantees that an error is returned. If the list of errors is
// empty, it will return the supplied error instead.
func NewOr(errs []error, fallback error) error {
if len(errs) == 0 {
return fallback
}
for _, err := range errs {
if err != nil {
return MultiError(errs)
}
}
return fallback
}
// Unwrap for MultiError always returns nil, as there is no reasonable way to implement it.
//
// Use As and Is methods, or loop over the list directly to access the underlying errors.
func (me MultiError) Unwrap() error {
return nil
}
// As for MultiError returns the first error that can be considered As the specified target.
func (me MultiError) As(target interface{}) bool {
for _, err := range me {
if errors.As(err, target) {
return true
}
}
return false
}
// Is for MultiError returns true if any of the errors listed can be considered of the target type.
func (me MultiError) Is(target error) bool {
for _, err := range me {
if errors.Is(err, target) {
return true
}
}
return false
}
func (me MultiError) Error() string {
if len(me) == 1 && me[0] != nil {
return me[0].Error()
}
messages := []string{}
for _, err := range me {
if err == nil {
continue
}
messages = append(messages, err.Error())
}
return "Multiple errors:\n " + strings.Join(messages, "\n ")
}