-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
error.go
79 lines (71 loc) · 1.86 KB
/
error.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
package pipe
import (
"errors"
"fmt"
"strings"
)
// CheckError returns 'err' if 'cond' is true, nil otherwise
func CheckError(cond bool, err error) error {
if cond {
return err
}
return nil
}
// CheckErrorf returns a new formatted error if 'cond' is true, nil otherwise
func CheckErrorf(cond bool, format string, args ...interface{}) error {
if cond {
return fmt.Errorf(format, args...)
}
return nil
}
// Error is an error returned from Pipe.Do().
// Can contain 1 or more errors. Conforms to the standard library's errors package interfaces like errors.As().
type Error struct {
errs []error
}
// Error implements the builtin error interface
func (e Error) Error() string {
if len(e.errs) == 1 {
return fmt.Sprintf("pipe: %v", e.errs[0])
}
errStrs := make([]string, len(e.errs))
for i, err := range e.errs {
errStrs[i] = err.Error()
}
return fmt.Sprintf("pipe: multiple errors: %s", strings.Join(errStrs, "; "))
}
// Unwrap implements errors.Unwrap() defined interface.
// Returns the first error. If there was not exactly 1 error, returns nil.
func (e Error) Unwrap() error {
if len(e.errs) != 1 {
// if there's not exactly 1 error, unwrapping no longer makes sense
return nil
}
return e.errs[0]
}
// As implements errors.As() defined interface
func (e Error) As(target interface{}) bool {
if len(e.errs) != 1 {
// if this error can't be effectively unwrapped to only 1 error, then fail error equivalence
return false
}
for _, candidate := range e.errs {
if errors.As(candidate, target) {
return true
}
}
return false
}
// Is implements errors.Is() defined interface
func (e Error) Is(target error) bool {
if len(e.errs) != 1 {
// if this error can't be effectively unwrapped to only 1 error, then fail error equivalence
return false
}
for _, candidate := range e.errs {
if errors.Is(candidate, target) {
return true
}
}
return false
}