-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathwrapper.go
57 lines (50 loc) · 1.25 KB
/
wrapper.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
package xerrors
import (
"errors"
"strings"
)
// WithWrapper wraps err with wrapper.
//
// The error used as wrapper should be a simple error, preferably a sentinel
// error. This is because details such as the wrapper's stack trace are ignored.
//
// The Unwrap method will unwrap only err but errors.Is, errors.As works with
// both of the errors.
//
// If wrapper is nil, then err is returned.
// If err is nil, then nil is returned.
func WithWrapper(wrapper error, err error) error {
if err == nil {
return nil
}
if wrapper == nil {
return err
}
return &withWrapper{
wrapper: wrapper,
err: err,
}
}
// withWrapper wraps an error with another error.
type withWrapper struct {
wrapper error
err error
}
// Error implements the error interface.
func (e *withWrapper) Error() string {
s := &strings.Builder{}
s.WriteString(e.wrapper.Error())
s.WriteString(": ")
s.WriteString(e.err.Error())
return s.String()
}
// Unwrap implements the Wrapper interface.
func (e *withWrapper) Unwrap() error {
return e.err
}
func (e *withWrapper) As(target interface{}) bool {
return errors.As(e.wrapper, target) || errors.As(e.err, target)
}
func (e *withWrapper) Is(target error) bool {
return errors.Is(e.wrapper, target) || errors.Is(e.err, target)
}