-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmulti_error.go
289 lines (250 loc) · 5.84 KB
/
multi_error.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Copyright The ActForGood Authors.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file or at
// https://github.com/actforgood/xerr/blob/main/LICENSE.
package xerr
import (
"bytes"
"errors"
"fmt"
"io"
"strconv"
"sync"
)
// MultiError holds a pool of errors.
// Its APIs are concurrent safe if you initialize it
// with [NewMultiError].
type MultiError struct {
errors []error
mu *sync.RWMutex
}
// NewMultiError instantiates a new MultiError object.
// Use it to initialize from start your MultiError variable
// if you use it in a concurrent context, or you need to pass it
// as parameter to a function. Otherwise just declare the variable's type
// and get effective instance returned by [MultiError.Add] / [MultiError.AddOnce] APIs,
// to avoid unnecessary allocation if those APIs end up never being called.
func NewMultiError() *MultiError {
return &MultiError{
errors: make([]error, 0),
mu: new(sync.RWMutex),
}
}
// newMultiError initializes internally a MultiError object, not concurrent safe.
func newMultiError() *MultiError {
return &MultiError{
errors: make([]error, 0),
}
}
// Error returns the error's message.
// Implements std error interface.
// Returns all stored errors' messages, new line separated.
func (mErr *MultiError) Error() string {
if mErr == nil {
return ""
}
mErr.rLock()
defer mErr.rUnlock()
switch len(mErr.errors) {
case 0:
return ""
case 1:
return mErr.errors[0].Error()
default:
buf := bytes.Buffer{}
for _, err := range mErr.errors {
buf.WriteString(err.Error())
buf.WriteByte('\n')
}
return string(buf.Bytes()[:buf.Len()-1])
}
}
// Add appends the given error(s) in MultiError.
// It returns the MultiError, eventually initialized.
func (mErr *MultiError) Add(errs ...error) *MultiError {
for _, err := range errs {
if err != nil {
if mErr == nil {
mErr = newMultiError()
}
mErr.lock()
mErr.errors = append(mErr.errors, err)
mErr.unlock()
}
}
return mErr
}
// AddOnce stores the given error(s) in MultiError,
// only if they do not exist already. Comparison is
// accomplished with [errors.Is] API.
// It returns the MultiError, eventually initialized.
func (mErr *MultiError) AddOnce(errs ...error) *MultiError {
for _, err := range errs {
if err == nil {
continue
}
if mErr == nil {
mErr = newMultiError()
}
mErr.lock()
if mErr.hasError(err) {
mErr.unlock()
continue
}
mErr.errors = append(mErr.errors, err)
mErr.unlock()
}
return mErr
}
// hasError checks if an error already exists in MultiError.
// Comparison is done with [errors.Is] API.
func (mErr *MultiError) hasError(err error) bool {
for _, storedErr := range mErr.errors {
if errors.Is(storedErr, err) {
return true
}
}
return false
}
// Errors returns a copy of stored errors.
func (mErr *MultiError) Errors() []error {
if mErr == nil {
return nil
}
mErr.rLock()
errors := make([]error, len(mErr.errors))
copy(errors, mErr.errors)
mErr.rUnlock()
return errors
}
// Reset cleans up stored errors, if any.
func (mErr *MultiError) Reset() {
if mErr == nil {
return
}
mErr.lock()
if len(mErr.errors) > 0 {
// keep the allocated memory
for idx := range mErr.errors {
mErr.errors[idx] = nil
}
mErr.errors = mErr.errors[:0]
}
mErr.unlock()
}
// ErrOrNil returns nil if MultiError does not have any stored errors,
// or the single error it stores,
// or self if has more more than 1 error.
func (mErr *MultiError) ErrOrNil() error {
if mErr == nil {
return nil
}
mErr.rLock()
defer mErr.rUnlock()
switch len(mErr.errors) {
case 0:
return nil
case 1:
return mErr.errors[0]
default:
return mErr
}
}
// Format implements [fmt.Formatter].
// It relies upon individual error's Format() API if applicable,
// otherwise Error() 's outcome is taken into account.
func (mErr *MultiError) Format(f fmt.State, verb rune) {
if mErr == nil {
return
}
mErr.rLock()
defer mErr.rUnlock()
errorsLen := len(mErr.errors)
if errorsLen == 0 {
return
}
for idx, err := range mErr.errors {
if verb == 'v' {
_, _ = io.WriteString(f, "error #")
_, _ = io.WriteString(f, strconv.FormatInt(int64(idx+1), 10))
_, _ = io.WriteString(f, "\n")
}
if errFmt, ok := err.(fmt.Formatter); ok {
errFmt.Format(f, verb)
} else {
_, _ = io.WriteString(f, err.Error())
}
if idx != errorsLen-1 {
_, _ = io.WriteString(f, "\n")
}
}
}
// Unwrap returns original error (can be nil).
// It implements standard [errors.Is] / [errors.As] APIs.
// Returns recursively first error from stored errors.
func (mErr *MultiError) Unwrap() error {
if mErr == nil {
return nil
}
mErr.rLock()
defer mErr.rUnlock()
if len(mErr.errors) == 0 {
return nil
} else if len(mErr.errors) == 1 {
return mErr.errors[0]
}
var newMultiErr *MultiError
if mErr.mu != nil {
newMultiErr = NewMultiError()
} else {
newMultiErr = newMultiError()
}
_ = newMultiErr.Add(mErr.errors[1:]...)
return newMultiErr
}
// As implements standard [errors.As] API,
// comparing the first error from stored ones.
func (mErr *MultiError) As(target interface{}) bool {
if mErr == nil {
return false
}
mErr.rLock()
defer mErr.rUnlock()
if len(mErr.errors) > 0 {
return errors.As(mErr.errors[0], target)
}
return false
}
// Is implements standard [errors.Is] API,
// comparing the first error from stored ones.
func (mErr *MultiError) Is(target error) bool {
if mErr == nil {
return mErr == target
}
mErr.rLock()
defer mErr.rUnlock()
if len(mErr.errors) > 0 {
return errors.Is(mErr.errors[0], target)
}
return false
}
func (mErr *MultiError) lock() {
if mErr.mu != nil {
mErr.mu.Lock()
}
}
func (mErr *MultiError) unlock() {
if mErr.mu != nil {
mErr.mu.Unlock()
}
}
func (mErr *MultiError) rLock() {
if mErr.mu != nil {
mErr.mu.RLock()
}
}
func (mErr *MultiError) rUnlock() {
if mErr.mu != nil {
mErr.mu.RUnlock()
}
}