-
Notifications
You must be signed in to change notification settings - Fork 1
/
wrap.go
84 lines (72 loc) · 1.71 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
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
83
84
package errors
import (
"errors"
"fmt"
"io"
"github.com/mailgun/errors/callstack"
)
// Wrap wraps the error and attaches stack information to the error
func Wrap(err error, msg string) error {
if err == nil {
return nil
}
return &wrappedError{
stack: callstack.New(1),
wrapped: err,
msg: msg,
}
}
// Wrapf is identical to Wrap but formats the error before wrapping.
func Wrapf(err error, format string, a ...any) error {
if err == nil {
return nil
}
return &wrappedError{
stack: callstack.New(1),
wrapped: err,
msg: fmt.Sprintf(format, a...),
}
}
// Cause returns the last error in the stack of wrapped errors.
func Cause(err error) error {
for {
wrapped := errors.Unwrap(err)
if wrapped == nil {
return err
}
err = wrapped
}
}
type wrappedError struct {
msg string
wrapped error
stack *callstack.CallStack
}
func (e *wrappedError) Unwrap() error {
return e.wrapped
}
func (e *wrappedError) Is(target error) bool {
_, ok := target.(*wrappedError)
return ok
}
// Cause returns the wrapped error which was the original
// cause of the issue. We only support this because some code
// depends on github.com/pkg/errors.Cause() returning the cause
// of the error.
// Deprecated: use error.Is() or error.As() instead
func (e *wrappedError) Cause() error { return e.wrapped }
func (e *wrappedError) Error() string {
if e.msg == NoMsg {
return e.wrapped.Error()
}
return e.msg + ": " + e.wrapped.Error()
}
func (e *wrappedError) StackTrace() callstack.StackTrace {
if child, ok := e.wrapped.(callstack.HasStackTrace); ok {
return child.StackTrace()
}
return e.stack.StackTrace()
}
func (e *wrappedError) Format(s fmt.State, verb rune) {
_, _ = io.WriteString(s, e.Error())
}