-
Notifications
You must be signed in to change notification settings - Fork 0
/
superr.go
123 lines (103 loc) · 2 KB
/
superr.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package superr
import (
"errors"
"fmt"
)
// New will build a tree of errors, for example, the underlining data structure
// will look like:
//
// Error{err: ErrFail, cause: Error{err: ErrNetwork; cause: Error{err: ErrWee, cause: nil}}}
func New(err error, causes ...error) error {
stack := &errStack{err: err}
if len(causes) == 0 {
return stack
}
parent := stack
for i := 0; i < len(causes); i++ {
child := &errStack{err: causes[i]}
parent.cause = child
if i == len(causes)-1 {
break
}
parent = child
}
return stack
}
// Wrap is synonymous with New, in case someone finds that name more familiar
// or intuitive.
func Wrap(err error, causes ...error) error {
return New(err, causes...)
}
type Error interface {
Err() error
}
type Cause interface {
Cause() error
}
type ErrorWithCause interface {
Error
Cause
}
var (
_ Error = &errStack{}
_ Cause = &errStack{}
)
type errStack struct {
err error
cause error
}
func (e errStack) Error() string {
if e.cause != nil {
return fmt.Sprintf("%s: %s", e.err, e.cause)
} else {
return fmt.Sprintf("%s", e.err)
}
}
func (e errStack) Err() error {
return e.err
}
func (e errStack) Cause() error {
return e.cause
}
func (e errStack) Unwrap() error {
return e.cause
}
func (e errStack) Is(target error) bool {
if e.err != nil && errors.Is(e.err, target) {
return true
}
if e.cause != nil && errors.Is(e.cause, target) {
return true
}
return false
}
// GetErrorStack returns the nested tree of errors from superr, in the form
// of a flat list.
func GetErrorStack(err error) []error {
if err == nil {
return []error{}
}
errs := []error{}
if e, ok := err.(ErrorWithCause); ok {
errs = append(errs, e.Err())
} else {
errs = append(errs, err)
}
for {
unwrap, ok := err.(interface{ Unwrap() error })
if !ok {
break
}
werr := unwrap.Unwrap()
if werr == nil {
break
}
if e, ok := werr.(ErrorWithCause); ok {
errs = append(errs, e.Err())
} else {
errs = append(errs, werr)
}
err = werr
}
return errs
}