-
Notifications
You must be signed in to change notification settings - Fork 1
/
chain.go
73 lines (65 loc) · 1.12 KB
/
chain.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
package echain
import (
"errors"
"strings"
)
type link struct {
err error
next *link
}
// ErrorChain will chain multiple errors
type ErrorChain struct {
head *link
tail *link
}
// New create a new error chain
func New() *ErrorChain {
return &ErrorChain{}
}
func (e *ErrorChain) Error() string {
errs := []string{}
h := e.head
for h != nil {
errs = append(errs, h.err.Error())
h = h.next
}
return strings.Join(errs, ": ")
}
// Unwrap will give the next error
func (e *ErrorChain) Unwrap() error {
if e.head.next == nil {
return nil
}
ec := &ErrorChain{
head: e.head.next,
tail: e.tail,
}
return ec
}
// Is will comapre the target
func (e *ErrorChain) Is(target error) bool {
return errors.Is(e.head.err, target)
}
// Add will place another error in the chain
func (e *ErrorChain) Add(err error) {
l := &link{
err: err,
}
if e.head == nil {
e.head = l
e.tail = l
return
}
e.tail.next = l
e.tail = l
}
// Errors will return the errors in the chain
func (e *ErrorChain) Errors() []error {
errs := []error{}
l := e.head
for l != nil {
errs = append(errs, l.err)
l = l.next
}
return errs
}