-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy patherrors.go
61 lines (50 loc) · 1.03 KB
/
errors.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
package bigopool
import (
"fmt"
"sync"
)
type (
// Errors is an interface for accessing a slice of errors.
Errors interface {
All() []error
ToError() error
IsEmpty() bool
}
// errs is a thread safe struct for appending a slice of errors.
errs struct {
mutex sync.Mutex
errs []error
}
)
// All returns the underlyings slice of errors.
func (ee *errs) All() []error {
return ee.errs
}
// ToError returns all errors as a single error.
func (ee *errs) ToError() error {
if len(ee.errs) == 0 {
return nil
}
err := ee.errs[0]
for _, otherErr := range ee.errs[1:] {
err = fmt.Errorf("%v; %w", err, otherErr)
}
return err
}
// IsEmpty is true if there are no errors.
func (ee *errs) IsEmpty() bool {
return len(ee.errs) == 0
}
// Error implements the error interface.
func (ee *errs) Error() string {
if len(ee.errs) == 0 {
return ""
}
return ee.ToError().Error()
}
// append safely appends to the error slice.
func (ee *errs) append(err error) {
ee.mutex.Lock()
ee.errs = append(ee.errs, err)
ee.mutex.Unlock()
}