-
Notifications
You must be signed in to change notification settings - Fork 0
/
stacktrace.go
56 lines (47 loc) · 1014 Bytes
/
stacktrace.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
package stacktrace
import (
"fmt"
"os"
"runtime"
)
const maxDepth = 5
// Propagate propagates errors up through the call stack.
func Propagate(err error, format string, args ...interface{}) *Error {
pc := make([]uintptr, maxDepth)
_ = runtime.Callers(2, pc[:])
frames := runtime.CallersFrames(pc)
serr := &Error{
wrapped: err,
cause: err,
message: fmt.Sprintf(format, args...),
frames: make([]frame, 0),
}
for {
f, more := frames.Next()
if !more {
break
}
serr.frames = append(serr.frames, frame{
file: f.File,
function: f.Function,
line: f.Line,
})
}
return serr
}
// Throw panics, recovers, and prints the stacktrace to standard out.
func Throw(err error) {
if r := recover(); r == nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
panic(err)
}
// Unwrap returns the wrapped error much like `github.com/pkg/errors`
// does (i.e. no stacktrace).
func Unwrap(err error) error {
if e, ok := err.(*Error); ok {
return e.Wrapped()
}
return err
}