-
Notifications
You must be signed in to change notification settings - Fork 0
/
error_group.go
105 lines (81 loc) · 2.38 KB
/
error_group.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
package error_group
import (
"errors"
"strings"
"sync"
)
type errorGroup struct {
mutex *sync.Mutex
errors []error
}
//goland:noinspection GoExportedFuncWithUnexportedType
func NewErrorGroup() *errorGroup {
errorMutex := sync.Mutex{}
return &errorGroup{
mutex: &errorMutex,
}
}
// Add adds an error to this error group instance.
func (eg *errorGroup) Add(err error) {
if err == nil {
return
}
eg.mutex.Lock()
defer eg.mutex.Unlock()
eg.errors = append(eg.errors, err)
return
}
// All returns a new slice containing every error in this error group instance.
func (eg *errorGroup) All() []error {
eg.mutex.Lock()
defer eg.mutex.Unlock()
duplicate := make([]error, len(eg.errors))
copy(duplicate, eg.errors)
return duplicate
}
// Error fulfills the builtin.Error interface and returns a concatenated string of all the errors in this error group instance.
func (eg *errorGroup) Error() string {
eg.mutex.Lock()
defer eg.mutex.Unlock()
if len(eg.errors) == 0 {
return ""
}
sb := strings.Builder{}
for _, currentError := range eg.errors {
sb.WriteString(currentError.Error())
sb.WriteString("\n")
}
return strings.TrimSuffix(sb.String(), "\n")
}
// First returns the first error saved to this error group instance. Since this
// library is thread safe - the first error saved is not deterministic if the
// library is used in a multithreaded environment.
func (eg *errorGroup) First() error {
eg.mutex.Lock()
defer eg.mutex.Unlock()
return eg.errors[0]
}
// Last returns the (current) last error saved to this error group instance.
// Subsequent calls to Add can cause the value returned here to no longer be the last.
func (eg *errorGroup) Last() error {
eg.mutex.Lock()
defer eg.mutex.Unlock()
return eg.errors[len(eg.errors)-1]
}
// Len returns the (current) length or number of errors saved to this error instance.
// Subsequent calls to Add can cause the value returned here to no longer be accurate.
func (eg *errorGroup) Len() int {
eg.mutex.Lock()
defer eg.mutex.Unlock()
return len(eg.errors)
}
// ToError is a convenience function that converts the errors contained in this
// error group into one single error. This is useful for returning the ErrorGroup
// object instance as a single generic builtin.Error interface instance.
func (eg *errorGroup) ToError() error {
errMessage := eg.Error()
if errMessage == "" {
return nil
}
return errors.New(errMessage)
}