-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi.go
128 lines (101 loc) · 2.03 KB
/
multi.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
package errors
import (
"bytes"
"errors"
"sync"
)
const (
defaultErrorGroupSeparator = " | "
)
// MultiError is list of errors.
type MultiError struct {
errors []error
mx sync.Mutex
}
// NewMultiError create new MultiError error.
func NewMultiError(errors ...error) *MultiError {
multi := &MultiError{}
for _, err := range errors {
multi.Add(err)
}
return multi
}
// Error sum of all errors.
func (m *MultiError) Error() string {
if m.Len() == 0 {
return ""
}
buffer := &bytes.Buffer{}
for index, err := range m.errors {
buffer.WriteString(err.Error())
if index < len(m.errors)-1 {
buffer.WriteString(defaultErrorGroupSeparator)
}
}
return buffer.String()
}
// Err of the multi error, return nil if no error is set.
func (m *MultiError) Err() error {
if m.Len() == 0 {
return nil
}
return m
}
// Errors return all list of errors.
func (m *MultiError) Errors() []error {
return m.errors
}
// Add new error to list.
func (m *MultiError) Add(err error) {
if err == nil {
return
}
m.errors = append(m.errors, err)
}
// SafeAdd is like add but concurrent safe.
func (m *MultiError) SafeAdd(err error) {
m.mx.Lock()
m.Add(err)
m.mx.Unlock()
}
// Len of errors.
func (m *MultiError) Len() int {
return len(m.errors)
}
// SafeLen is like len but concurrent safe.
func (m *MultiError) SafeLen() int {
m.mx.Lock()
defer m.mx.Unlock()
return len(m.errors)
}
// Unwrap return cause error (first error in list).
func (m *MultiError) Unwrap() error {
if len(m.errors) == 0 {
return nil
}
m.mx.Lock()
defer m.mx.Unlock()
return m.errors[0]
}
// Is check errors for match.
func (m *MultiError) Is(err error) bool {
m.mx.Lock()
defer m.mx.Unlock()
for i := range m.errors {
if errors.Is(err, m.errors[i]) {
return true
}
}
return false
}
// As implements errors.As by attempting to map to the current value.
func (m *MultiError) As(target interface{}) bool {
m.mx.Lock()
defer m.mx.Unlock()
for i := range m.errors {
if errors.As(m.errors[i], target) {
return true
}
}
return false
}