-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathwrap.go
53 lines (45 loc) · 1.24 KB
/
wrap.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
package errors
// Unwrap returns the result of calling the Unwrap method on err, if err implements
// Unwrap. Otherwise, Unwrap returns nil.
//
// It supports both Go 1.13 Unwrap and github.com/pkg/errors.Causer interfaces
// (the former takes precedence).
func Unwrap(err error) error {
switch e := err.(type) {
case interface{ Unwrap() error }:
return e.Unwrap()
case interface{ Cause() error }:
return e.Cause()
}
return nil
}
// UnwrapEach loops through an error chain and calls a function for each of them.
//
// The provided function can return false to break the loop before it reaches the end of the chain.
//
// It supports both Go 1.13 errors.Wrapper and github.com/pkg/errors.Causer interfaces
// (the former takes precedence).
func UnwrapEach(err error, fn func(err error) bool) {
for err != nil {
continueLoop := fn(err)
if !continueLoop {
break
}
err = Unwrap(err)
}
}
// Cause returns the last error (root cause) in an err's chain.
// If err has no chain, it is returned directly.
//
// It supports both Go 1.13 errors.Wrapper and github.com/pkg/errors.Causer interfaces
// (the former takes precedence).
func Cause(err error) error {
for {
cause := Unwrap(err)
if cause == nil {
break
}
err = cause
}
return err
}