-
Notifications
You must be signed in to change notification settings - Fork 0
/
errchain.go
55 lines (43 loc) · 1.03 KB
/
errchain.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
package errchain
import "errors"
type chain struct {
error
next error
}
// New builds a chain of errors.
func New(errs ...error) error {
if len(errs) == 0 {
return nil
}
if len(errs) == 1 {
return errs[0]
}
return chain{
error: errs[0],
next: New(errs[1:]...),
}
}
// Error returns string with concatenated underlying errors
// strings, nested in "(" and ")".
func (c chain) Error() string {
if c.error == nil && c.next == nil {
return ""
}
if c.error == nil {
return c.next.Error()
}
if c.next == nil {
return c.error.Error()
}
return c.error.Error() + " (" + c.next.Error() + ")"
}
// Is examines a chain for compliance with any error.
func (c chain) Is(target error) bool {
return errors.Is(c.error, target) || errors.Is(c.next, target)
}
// As finds the first error in a chain that matches target, and
// if one is found, sets target to that error value and returns
// true. Otherwise, it returns false.
func (c chain) As(target any) bool {
return errors.As(c.error, target) || errors.As(c.next, target)
}