This repository has been archived by the owner on Aug 14, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmultierr.go
82 lines (67 loc) · 2.1 KB
/
multierr.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
package emperror
// Errors is responsible for listing multiple errors.
type Errors interface {
// Errors returns the list of wrapped errors.
Errors() []error
}
// multiError implements Errors and aggregates multiple errors into a single value.
// Also implements the error interface so it can be returned as an error.
type multiError struct {
errors []error
msg string
}
// Error implements the error interface.
func (e *multiError) Error() string {
if e.msg != "" {
return e.msg
}
return "Multiple errors happened"
}
// Errors returns the list of wrapped errors.
func (e *multiError) Errors() []error {
return e.errors
}
// SingleWrapMode defines how MultiErrorBuilder behaves when there is only one error in the list.
type SingleWrapMode int
// These constants cause MultiErrorBuilder to behave as described if there is only one error in the list.
const (
AlwaysWrap SingleWrapMode = iota // Always return a multiError.
ReturnSingle // Return the single error.
)
// MultiErrorBuilder provides an interface for aggregating errors and exposing them as a single value.
type MultiErrorBuilder struct {
errors []error
Message string
SingleWrapMode SingleWrapMode
}
// NewMultiErrorBuilder returns a new MultiErrorBuilder.
func NewMultiErrorBuilder() *MultiErrorBuilder {
return &MultiErrorBuilder{
SingleWrapMode: AlwaysWrap,
}
}
// Add adds an error to the list.
//
// Calling this method concurrently is not safe.
func (b *MultiErrorBuilder) Add(err error) {
// Do not add nil values.
if err == nil {
return
}
b.errors = append(b.errors, err)
}
// ErrOrNil returns a multiError the builder aggregates a list of errors,
// or returns nil if the list of errors is empty.
//
// It is useful to avoid checking if there are any errors added to the list.
func (b *MultiErrorBuilder) ErrOrNil() error {
// No errors added, return nil.
if len(b.errors) == 0 {
return nil
}
// Return a single error when there is only one and the builder is told to do so.
if len(b.errors) == 1 && b.SingleWrapMode == ReturnSingle {
return b.errors[0]
}
return &multiError{b.errors, b.Message}
}