-
Notifications
You must be signed in to change notification settings - Fork 0
/
join.go
93 lines (73 loc) · 1.21 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
package errs
import (
"errors"
"strings"
)
const (
defaultSeparator = ": "
)
func Join(e ...error) error {
return join(defaultSeparator, e...)
}
func JoinWith(sep string, e ...error) error {
if sep == "" {
sep = defaultSeparator
}
return join(sep, e...)
}
func compact(e ...error) []error {
n := 0
for _, err := range e {
if err != nil {
n++
}
}
if n == 0 {
return nil
}
output := make([]error, 0, n)
for i := range e {
if e[i] != nil {
output = append(output, e[i])
}
}
return output
}
func join(sep string, e ...error) error {
e = compact(e...)
switch len(e) {
case 0:
return nil
case 1:
return e[0]
}
sb := &strings.Builder{}
for i := range e {
printError(sb, e[i])
if i < len(e)-1 {
sb.WriteString(sep)
}
}
return joinedError{
errString: sb.String(),
e: e,
}
}
func printError(sb *strings.Builder, err error) {
var withDomain sentinelWithDomain
if errors.As(err, &withDomain) {
sb.WriteString(withDomain.sentinel.errString)
return
}
sb.WriteString(err.Error())
}
type joinedError struct {
errString string
e []error
}
func (e joinedError) Error() string {
return e.errString
}
func (e joinedError) Unwrap() []error {
return e.e
}