-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmultierror.go
117 lines (107 loc) · 2.42 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package xerrors
import (
"errors"
"strconv"
"strings"
)
// Append adds more errors to an existing list of errors. If err is not a list
// of errors, then it will be converted into a list. Nil errors are ignored.
// It does not record a stack trace.
//
// If the list is empty, nil is returned. If the list contains only one error,
// that error is returned instead of list.
//
// The returned list of errors is compatible with Go 1.13 errors, and it
// supports the errors.Is and errors.As methods. However, the errors.Unwrap
// method is not supported.
//
// Append is not thread-safe.
func Append(err error, errs ...error) error {
if err == nil && len(errs) == 0 {
return nil
}
switch errTyp := err.(type) {
case multiError:
for _, e := range errs {
if e != nil {
errTyp = append(errTyp, e)
}
}
return errTyp
default:
var me multiError
if err != nil {
me = multiError{err}
}
for _, e := range errs {
if e != nil {
me = append(me, e)
}
}
if len(me) == 1 {
return me[0]
}
if len(me) == 0 {
return nil
}
return me
}
}
const multiErrorErrorPrefix = "the following errors occurred: "
// multiError is a slice of errors that can be used as a single error.
type multiError []error
// Error implements the error interface.
func (e multiError) Error() string {
s := &strings.Builder{}
s.WriteString(multiErrorErrorPrefix)
s.WriteString("[")
for n, err := range e {
s.WriteString(err.Error())
if n < len(e)-1 {
s.WriteString(", ")
}
}
s.WriteString("]")
return s.String()
}
// ErrorDetails implements the DetailedError interface.
func (e multiError) ErrorDetails() string {
s := &strings.Builder{}
for n, err := range e.Errors() {
s.WriteString(strconv.Itoa(n + 1))
s.WriteString(". ")
s.WriteString(indent(Sprint(err)))
}
return s.String()
}
// Errors implements the MultiError interface.
func (e multiError) Errors() []error {
s := make([]error, len(e))
copy(s, e)
return s
}
func (e multiError) As(target interface{}) bool {
for _, err := range e {
if errors.As(err, target) {
return true
}
}
return false
}
func (e multiError) Is(target error) bool {
for _, err := range e {
if errors.Is(err, target) {
return true
}
}
return false
}
// indent idents every line, except the first one, with tab.
func indent(s string) string {
end := ""
if strings.HasSuffix(s, "\n") {
end = "\n"
s = s[:len(s)-1]
}
return strings.ReplaceAll(s, "\n", "\n\t") + end
}