-
Notifications
You must be signed in to change notification settings - Fork 1
/
join.go
97 lines (87 loc) · 1.47 KB
/
join.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
package errors
import (
"fmt"
"io"
"strings"
"sync"
)
func Join(errs ...error) error {
if len(errs) == 0 {
return nil
}
e := &withJoin{errs: make([]error, 0, len(errs))}
for _, err := range errs {
if err != nil {
e.errs = append(e.errs, err)
}
}
if len(e.errs) == 0 {
return nil
}
return e
}
func NewWithJoin(errs ...error) ErrorJoin {
e := &withJoin{errs: make([]error, 0, len(errs))}
for _, err := range errs {
if err != nil {
e.errs = append(e.errs, err)
}
}
return e
}
type ErrorJoin interface {
error
Append(error)
Unwrap() []error
}
type withJoin struct {
errs []error
mu sync.Mutex
}
func (w *withJoin) Error() string {
if len(w.errs) == 0 {
return ""
}
var builder strings.Builder
builder.WriteString(w.errs[0].Error())
for _, err := range w.errs[1:] {
builder.WriteByte('\n')
builder.WriteString(err.Error())
}
return builder.String()
}
func (w *withJoin) Append(err error) {
if err == nil {
return
}
w.mu.Lock()
defer w.mu.Unlock()
w.errs = append(w.errs, err)
}
func (w *withJoin) Is(err error) bool {
for _, e := range w.errs {
if Is(e, err) {
return true
}
}
return false
}
func (w *withJoin) Unwrap() []error {
return w.errs
}
func (w *withJoin) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
for _, err := range w.errs {
fmt.Fprintf(s, "%+v\n", err)
}
return
}
fallthrough
case 's', 'q':
for _, err := range w.errs {
io.WriteString(s, err.Error())
}
}
}