-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathwrapper.go
More file actions
68 lines (61 loc) · 1.84 KB
/
wrapper.go
File metadata and controls
68 lines (61 loc) · 1.84 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
package xerrors
import (
"errors"
"strings"
)
// withWrapper wraps one error with another.
//
// It is intended to build error chains. For example, given an error chain
// like `err1: err2: err3`, the wrapper is `err1`, and the err is another
// withWrapper containing `err2` and `err3`.
type withWrapper struct {
wrapper error // wrapper is the error that wraps the next error in the chain, may be nil
err error // err is the next error in the chain, must not be nil
msg string // msg overwrites the error message, if set
}
// Error implements the [error] interface.
func (e *withWrapper) Error() string {
if e.msg != "" {
return e.msg
}
s := &strings.Builder{}
if e.wrapper != nil {
s.WriteString(e.wrapper.Error())
s.WriteString(": ")
}
s.WriteString(e.err.Error())
return s.String()
}
// ErrorDetails implements the [DetailedError] interface.
func (e *withWrapper) ErrorDetails() string {
err := e.wrapper
for err != nil {
if dErr, ok := err.(DetailedError); ok {
return dErr.ErrorDetails()
}
if wErr, ok := err.(interface{ Unwrap() error }); ok {
err = wErr.Unwrap()
continue
}
break
}
return ""
}
// Unwrap implements the Go 1.13 `Unwrap() error` method, returning
// the wrapped error.
//
// Since withWrapper represents a chain of errors, the Unwrap method
// returns the next error in the chain, not both the wrapper and the error.
func (e *withWrapper) Unwrap() error {
return e.err
}
// As implements the Go 1.13 `errors.As` method, allowing type
// assertions on all errors in the list.
func (e *withWrapper) As(target any) bool {
return errors.As(e.wrapper, target) || errors.As(e.err, target)
}
// Is implements the Go 1.13 `errors.Is` method, allowing
// comparisons with all errors in the list.
func (e *withWrapper) Is(target error) bool {
return errors.Is(e.wrapper, target) || errors.Is(e.err, target)
}