-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstack.go
More file actions
88 lines (73 loc) · 1.49 KB
/
stack.go
File metadata and controls
88 lines (73 loc) · 1.49 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package errs
import (
"errors"
"github.com/tehsphinx/cstack"
)
// WithStack adds a call stack to the error.
func WithStack(err error) error {
if err == nil {
return nil
}
return withStack(err)
}
func withStack(err error) error {
if errors.Is(err, stackError{}) {
// already has a stack
return err
}
const skipStack = 4
return stackError{
err: err,
stack: cstack.CallStack(skipStack),
}
}
type stackError struct {
err error
stack cstack.Stack
}
func (s stackError) Error() string {
return s.err.Error()
}
func (s stackError) Unwrap() error {
return s.err
}
// GetStack returns the stack from the error chain if there was one added using WithStack.
func GetStack(err error) (cstack.Stack, bool) {
var r stackError
if !errors.As(err, &r) {
return nil, false
}
return r.stack, true
}
// FormatStack implements marshalling of the error stack.
//
// Usage with zerolog:
//
// zerolog.ErrorStackMarshaler = func(err error) interface{} {
// stack := FormatStack(err)
// if stack == "" {
// return nil
// }
// return stack
// }
func FormatStack(err error) string {
st, ok := GetStack(err)
if !ok {
return ""
}
return st.DefaultFormat()
}
// StackFrameInfo implements marshalling of the error stack as a slice of frames.
//
// Usage with zerolog:
//
// zerolog.ErrorStackMarshaler = func(err error) interface{} {
// return StackInfo(err)
// }
func StackFrameInfo(err error) []cstack.FrameInfo {
st, ok := GetStack(err)
if !ok {
return nil
}
return st.StackInfo()
}