-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patherrors.go
More file actions
84 lines (67 loc) · 1.32 KB
/
errors.go
File metadata and controls
84 lines (67 loc) · 1.32 KB
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
package otk
import (
"strings"
"sync"
"golang.org/x/xerrors"
)
// MergeErrors merges a slice of errors, but they will lose any context.
// returns nil if all errors are nil
func MergeErrors(sep string, errs ...error) error {
var buf strings.Builder
for _, err := range errs {
if err == nil {
continue
}
if buf.Len() > 0 {
buf.WriteString(sep)
}
buf.WriteString(err.Error())
}
if buf.Len() == 0 {
return nil
}
return xerrors.New(buf.String())
}
type ErrorList []error
func (el ErrorList) Error() string { return MergeErrors(" | ", el...).Error() }
func (el ErrorList) Len() int { return len(el) }
func (el ErrorList) Err() error {
if len(el) == 0 {
return nil
}
return el[:len(el):len(el)]
}
func (el *ErrorList) Push(errs ...error) {
for _, err := range errs {
if err != nil {
*el = append(*el, err)
}
}
}
type SafeErrorList struct {
mux sync.Mutex
el ErrorList
}
func (el *SafeErrorList) Error() string {
el.mux.Lock()
err := el.el.Error()
el.mux.Unlock()
return err
}
func (el *SafeErrorList) Len() int {
el.mux.Lock()
ln := len(el.el)
el.mux.Unlock()
return ln
}
func (el *SafeErrorList) Err() error {
el.mux.Lock()
err := el.el.Err()
el.mux.Unlock()
return err
}
func (el *SafeErrorList) Push(errs ...error) {
el.mux.Lock()
el.el.Push(errs...)
el.mux.Unlock()
}