-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack_trace.go
70 lines (54 loc) · 1.19 KB
/
stack_trace.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
package errlog
import (
"runtime"
"strconv"
"strings"
)
// StackTracer is an interface that represents an error that can provide a stack trace.
type StackTracer interface {
Stack() []uintptr
}
func formatStack(stack []uintptr) string {
frames := runtime.CallersFrames(stack)
var sb strings.Builder
for {
frame, more := frames.Next()
sb.WriteString(frame.Function)
sb.WriteString("\n\t")
sb.WriteString(frame.File)
sb.WriteString(":")
sb.WriteString(strconv.Itoa(frame.Line))
sb.WriteString("\n")
if !more {
break
}
}
return sb.String()
}
type withStackTraceError struct {
err error
stack []uintptr
}
var (
_ error = (*withStackTraceError)(nil)
_ StackTracer = (*withStackTraceError)(nil)
)
func wrapError(err error, additionalSkip int) error {
const skipCount = 2
const depth = 16
stack := make([]uintptr, depth)
frameCount := runtime.Callers(skipCount+additionalSkip, stack)
return &withStackTraceError{
err: err,
stack: stack[:frameCount],
}
}
func (e withStackTraceError) Error() string {
return e.err.Error()
}
func (e withStackTraceError) Unwrap() error {
return e.err
}
func (e withStackTraceError) Stack() []uintptr {
return e.stack
}