-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstacktrace.go
More file actions
227 lines (205 loc) · 5.11 KB
/
stacktrace.go
File metadata and controls
227 lines (205 loc) · 5.11 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
package xerrors
import (
"fmt"
"io"
"runtime"
"strconv"
"strings"
)
// DefaultCallersFormatter is the default formatter for [Callers].
var DefaultCallersFormatter = func(c Callers, w io.Writer) {
for _, frame := range c.Frames() {
io.WriteString(w, "at ")
frame.writeFrame(w)
io.WriteString(w, "\n")
}
}
// DefaultFrameFormatter is the default formatter for [Frame].
var DefaultFrameFormatter = func(f Frame, w io.Writer) {
io.WriteString(w, shortname(f.Function))
io.WriteString(w, " (")
io.WriteString(w, f.File)
io.WriteString(w, ":")
io.WriteString(w, strconv.Itoa(f.Line))
io.WriteString(w, ")")
}
const stackTraceDepth = 128
// StackTrace extracts the stack trace from the provided error.
// It traverses the error chain, looking for the last error that
// has a stack trace.
func StackTrace(err error) Callers {
var callers Callers
for err != nil {
if st, ok := err.(interface{ StackTrace() Callers }); ok {
callers = st.StackTrace()
}
if wErr, ok := err.(interface{ Unwrap() error }); ok {
err = wErr.Unwrap()
continue
}
break
}
return callers
}
// WithStackTrace wraps the provided error with a stack trace,
// capturing the stack at the point of the call. The `skip` argument
// specifies how many stack frames to skip.
//
// If err is nil, WithStackTrace returns nil.
func WithStackTrace(err error, skip int) error {
if err == nil {
return nil
}
return &withStackTrace{
err: err,
stack: callers(skip + 1),
}
}
// withStackTrace wraps an error with a captured stack trace.
type withStackTrace struct {
err error
stack Callers
}
// Error implements the [error] interface.
func (e *withStackTrace) Error() string {
return e.err.Error()
}
// ErrorDetails implements the [DetailedError] interface.
func (e *withStackTrace) ErrorDetails() string {
return e.stack.String()
}
// Unwrap implements the Go 1.13 `Unwrap() error` method, returning
// the wrapped error.
func (e *withStackTrace) Unwrap() error {
return e.err
}
// StackTrace returns the stack trace captured at the point of the
// error creation.
func (e *withStackTrace) StackTrace() Callers {
return e.stack
}
// Frame represents a single stack frame with file, line, and
// function details.
type Frame struct {
File string
Line int
Function string
}
// String implements the [fmt.Stringer] interface.
func (f Frame) String() string {
s := &strings.Builder{}
f.writeFrame(s)
return s.String()
}
// Format implements the [fmt.Formatter] interface.
//
// Supported verbs:
// - %s function, file, and line number in a single line
// - %f filename
// - %d line number
// - %n function name, with '+' flag adding the package name
// - %v same as %s; '+' or '#' flags print struct details
// - %q double-quoted Go string, same as %s
func (f Frame) Format(s fmt.State, verb rune) {
type _Frame Frame
switch verb {
case 's':
f.writeFrame(s)
case 'f':
io.WriteString(s, f.File)
case 'd':
io.WriteString(s, strconv.Itoa(f.Line))
case 'n':
switch {
case s.Flag('+'):
io.WriteString(s, f.Function)
default:
io.WriteString(s, shortname(f.Function))
}
case 'v':
switch {
case s.Flag('+') || s.Flag('#'):
format(s, verb, _Frame(f))
default:
f.Format(s, 's')
}
case 'q':
io.WriteString(s, strconv.Quote(f.String()))
default:
format(s, verb, _Frame(f))
}
}
// writeFrame writes a formatted stack frame to the given [io.Writer].
func (f Frame) writeFrame(w io.Writer) {
DefaultFrameFormatter(f, w)
}
// Callers represents a list of program counters from the
// [runtime.Callers] function.
type Callers []uintptr
// Frames returns a slice of [Frame] structs with function, file, and
// line information.
func (c Callers) Frames() []Frame {
r := make([]Frame, len(c))
f := runtime.CallersFrames(c)
n := 0
for {
frame, more := f.Next()
r[n] = Frame{
File: frame.File,
Line: frame.Line,
Function: frame.Function,
}
if !more {
break
}
n++
}
return r
}
// String implements the [fmt.Stringer] interface.
func (c Callers) String() string {
s := &strings.Builder{}
c.writeTrace(s)
return s.String()
}
// Format implements the [fmt.Formatter] interface.
//
// Supported verbs:
// - %s complete stack trace
// - %v same as %s; '+' or '#' flags print struct details
// - %q double-quoted Go string, same as %s
func (c Callers) Format(s fmt.State, verb rune) {
type _Callers Callers
switch verb {
case 's':
c.writeTrace(s)
case 'v':
switch {
case s.Flag('+') || s.Flag('#'):
format(s, verb, _Callers(c))
default:
c.Format(s, 's')
}
case 'q':
io.WriteString(s, strconv.Quote(c.String()))
default:
format(s, verb, _Callers(c))
}
}
// writeTrace writes the stack trace to the provided [io.Writer].
func (c Callers) writeTrace(w io.Writer) {
DefaultCallersFormatter(c, w)
}
// callers captures the current stack trace, skipping the specified
// number of frames.
func callers(skip int) Callers {
b := make([]uintptr, stackTraceDepth)
l := runtime.Callers(skip+2, b[:])
return b[:l]
}
// shortname extracts the short name of a function, removing the
// package path.
func shortname(name string) string {
i := strings.LastIndex(name, "/")
return name[i+1:]
}