-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmatch.go
More file actions
82 lines (64 loc) · 2.04 KB
/
match.go
File metadata and controls
82 lines (64 loc) · 2.04 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
package match
import (
"reflect"
"emperror.dev/errors"
)
// ErrorMatcher checks if an error matches a certain condition.
type ErrorMatcher interface {
// MatchError checks if err matches a certain condition.
MatchError(err error) bool
}
// ErrorMatcherFunc turns a plain function into an ErrorMatcher if it's definition matches the interface.
type ErrorMatcherFunc func(err error) bool
// MatchError calls the underlying function to check if err matches a certain condition.
func (fn ErrorMatcherFunc) MatchError(err error) bool {
return fn(err)
}
// Any matches an error if any of the underlying matchers match it.
type Any []ErrorMatcher
// MatchError calls underlying matchers with err.
// If any of them matches err it returns true, otherwise false.
func (m Any) MatchError(err error) bool {
for _, matcher := range m {
if matcher.MatchError(err) {
return true
}
}
return false
}
// All matches an error if all of the underlying matchers match it.
type All []ErrorMatcher
// MatchError calls underlying matchers with err.
// If all of them matches err it returns true, otherwise false.
func (m All) MatchError(err error) bool {
for _, matcher := range m {
if !matcher.MatchError(err) {
return false
}
}
return true
}
// Is returns an error matcher that determines matching by calling errors.Is.
func Is(target error) ErrorMatcher {
return ErrorMatcherFunc(func(err error) bool {
return errors.Is(err, target)
})
}
// As returns an error matcher that determines matching by calling errors.As.
func As(target interface{}) ErrorMatcher {
if target == nil {
panic("errors: target cannot be nil")
}
val := reflect.ValueOf(target)
typ := val.Type()
if typ.Kind() != reflect.Ptr || val.IsNil() {
panic("errors: target must be a non-nil pointer")
}
if e := typ.Elem(); e.Kind() != reflect.Interface && !e.Implements(errorType) {
panic("errors: *target must be interface or implement error")
}
return ErrorMatcherFunc(func(err error) bool {
return errors.As(err, target)
})
}
var errorType = reflect.TypeOf((*error)(nil)).Elem()