-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbundlerr.go
More file actions
95 lines (77 loc) · 1.77 KB
/
bundlerr.go
File metadata and controls
95 lines (77 loc) · 1.77 KB
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
// Package bundlerr let's you bundle multiple errors into one
package bundlerr
import (
"errors"
)
type Bundle struct {
errors []error
formatter Formatter
}
func New(errs ...error) *Bundle {
return NewWithFormatter(defaultFormatFn, errs...)
}
func NewWithFormatter(formatter Formatter, errs ...error) *Bundle {
return &Bundle{
errors: errs,
formatter: formatter,
}
}
// Append appends new error to the bundle. If the new error is nil, it is ignore
// if the new error is another bundle, their errors are merged into this bundle creating flat structure
func (b *Bundle) Append(e error) {
if e == nil {
return
}
if b == e {
return
}
if bundle, ok := e.(*Bundle); ok {
b.errors = append(b.errors, bundle.errors...)
return
} else if bundle, ok := e.(Bundle); ok {
b.errors = append(b.errors, bundle.errors...)
return
}
b.errors = append(b.errors, e)
}
// Evaluate evaluates the bundle to nil if no errors are bundled or returns the bundle
func (b *Bundle) Evaluate() error {
if b == nil || len(b.errors) == 0 {
return nil
}
return b
}
// Errors returns all errors in this bundle
func (b *Bundle) Errors() []error {
if b == nil {
return []error{}
}
return b.errors
}
func (b Bundle) Error() string {
return b.formatter(b)
}
// Is returns true if any of the bundled errors is the target error - same as errors.Is
func (b *Bundle) Is(target error) bool {
if b == nil {
return false
}
for _, err := range b.errors {
if errors.Is(err, target) {
return true
}
}
return false
}
// As returns true if any of the bundled errors are the target error - same as errors.As
func (b *Bundle) As(target interface{}) bool {
if b == nil {
return false
}
for _, err := range b.errors {
if errors.As(err, target) {
return true
}
}
return false
}