forked from DeltaVML/parallel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
errors.go
64 lines (55 loc) · 1.23 KB
/
errors.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
package parallel
import (
"strings"
)
// MultiError is used internally to wrap multiple errors that occur
// within a function
type MultiError interface {
error
Unwrap() []error
One() error
}
type multiError struct {
errors []error
}
func (e *multiError) Error() string {
return strings.Join(e.errorStrings(), "\n")
}
func (e *multiError) Unwrap() []error {
return e.errors
}
func (e *multiError) errorStrings() (strings []string) {
for _, err := range e.errors {
if err != nil {
strings = append(strings, err.Error())
}
}
return
}
func (e *multiError) One() error {
return e.errors[0]
}
func NewMultiError(errs ...error) MultiError {
if len(errs) > 0 {
return &multiError{errors: errs} // concrete type not exposed
}
return nil
}
// Combine multiple errors into one MultiError, discarding all nil errors and
// flattening any existing MultiErrors. If the result has no errors, the result
// is nil.
func CombineErrors(errs ...error) MultiError {
var combined []error
for _, err := range errs {
if err == nil {
continue
}
switch typedErr := err.(type) {
case MultiError:
combined = append(combined, typedErr.Unwrap()...)
default:
combined = append(combined, err)
}
}
return NewMultiError(combined...)
}