-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwrapwithcallstack.go
71 lines (59 loc) · 1.67 KB
/
wrapwithcallstack.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
package errs
import (
"fmt"
"runtime"
)
// New returns a new error with the passed text
// wrapped with the current call stack.
func New(text string) error {
return WrapWithCallStackSkip(1, Sentinel(text))
}
// Errorf wraps the result of fmt.Errorf with the current call stack.
//
// If the format specifier includes a %w verb with an error operand,
// the returned error will implement an Unwrap method returning the operand. It is
// invalid to include more than one %w verb or to supply it with an operand
// that does not implement the error interface. The %w verb is otherwise
// a synonym for %v.
func Errorf(format string, a ...any) error {
return WrapWithCallStackSkip(1, fmt.Errorf(format, a...))
}
// WrapWithCallStack wraps an error with the current call stack.
func WrapWithCallStack(err error) error {
return WrapWithCallStackSkip(1, err)
}
// WrapWithCallStackSkip wraps an error with the current call stack
// skipping skip stack frames.
func WrapWithCallStackSkip(skip int, err error) error {
return &withCallStack{
err: err,
callStack: callStack(1 + skip),
}
}
type callStackProvider interface {
Unwrap() error
CallStack() []uintptr
}
var (
_ error = &withCallStack{}
_ callStackProvider = &withCallStack{}
)
// withCallStack is an error wrapper that implements callStackProvider
type withCallStack struct {
err error
callStack []uintptr
}
func (w *withCallStack) Error() string {
return formatError(w)
}
func (w *withCallStack) Unwrap() error {
return w.err
}
func (w *withCallStack) CallStack() []uintptr {
return w.callStack
}
func callStack(skip int) []uintptr {
c := make([]uintptr, 32)
n := runtime.Callers(skip+2, c)
return c[:n]
}