-
Notifications
You must be signed in to change notification settings - Fork 31
/
utils.go
61 lines (52 loc) · 1.6 KB
/
utils.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
package errorx
// Cast attempts to cast an error to errorx Type, returns nil if cast has failed.
func Cast(err error) *Error {
if e, ok := err.(*Error); ok && e != nil {
return e
}
return nil
}
// Ignore returns nil if an error is of one of the provided types, returns the provided error otherwise.
// May be used if a particular error signifies a mark in control flow rather than an error to be reported to the caller.
func Ignore(err error, types ...*Type) error {
if e := Cast(err); e != nil {
for _, t := range types {
if e.IsOfType(t) {
return nil
}
}
}
return err
}
// IgnoreWithTrait returns nil if an error has one of the provided traits, returns the provided error otherwise.
// May be used if a particular error trait signifies a mark in control flow rather than an error to be reported to the caller.
func IgnoreWithTrait(err error, traits ...Trait) error {
if e := Cast(err); e != nil {
for _, t := range traits {
if e.HasTrait(t) {
return nil
}
}
}
return err
}
// GetTypeName returns the full type name if an error; returns an empty string for non-errorx error.
// For decorated errors, the type of an original cause is used.
func GetTypeName(err error) string {
if e := Cast(err); e != nil {
t := e.Type()
if t != foreignType {
return t.FullName()
}
}
return ""
}
// ReplicateError is a utility function to duplicate error N times.
// May be handy do demultiplex a single original error to a number of callers/requests.
func ReplicateError(err error, count int) []error {
result := make([]error, count)
for i := range result {
result[i] = err
}
return result
}