-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathErrorsWithTrace.go
58 lines (44 loc) · 1.37 KB
/
ErrorsWithTrace.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
//! To use this, wrap every error return with `WithStack`
//! To enable stack traces set `SHOW_ERROR_STACK_TRACES` environment variable to `true`
package utils
import (
"unsafe"
"runtime"
)
// when this is true, errors will have stack trace
// changing this to `const show = false` should eliminate any performance penalty
var show = false
// Max size of the stak trace
const maxTraceLen = 1024 * 16
type ErrorWithStack struct {
current string
originalLen int
original error
}
func (e ErrorWithStack) Error() string { return e.current }
func (e ErrorWithStack) Unwrap() error { return e.original }
func (e ErrorWithStack) OriginalError() string { return e.current[:e.originalLen] }
func noStack(err error) error { return err }
func withStack(err error) error {
if err == nil { return nil }
if _, ok := err.(ErrorWithStack); ok { return err }
out := make([]byte, maxTraceLen, maxTraceLen)
originalString := err.Error()
return ErrorWithStack{
current: originalString + "\n##-STACK-##\n" + unsafe.String(unsafe.SliceData(out), runtime.Stack(out, false)),
originalLen: len(originalString),
original: err,
}
}
var WithStack = noStack
func SetErrorStackTrace(showTrace bool) {
if show == showTrace { return }
show = showTrace
if show {
runtime.StartTrace()
WithStack = withStack
} else {
WithStack = noStack
runtime.StopTrace()
}
}