-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy patherror.go
95 lines (76 loc) · 1.54 KB
/
error.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
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
package honeybadger
import (
"errors"
"fmt"
"reflect"
"runtime"
"strconv"
)
const maxFrames = 20
// Frame represent a stack frame inside of a Honeybadger backtrace.
type Frame struct {
Number string `json:"number"`
File string `json:"file"`
Method string `json:"method"`
}
// Error provides more structured information about a Go error.
type Error struct {
err error
Message string
Class string
Stack []*Frame
}
func (e Error) Unwrap() error {
return e.err
}
func (e Error) Error() string {
return e.Message
}
type stacked interface {
Callers() []uintptr
}
func NewError(msg interface{}) Error {
return newError(msg, 2)
}
func newError(thing interface{}, stackOffset int) Error {
var err error
switch t := thing.(type) {
case Error:
return t
case error:
err = t
default:
err = fmt.Errorf("%v", t)
}
return Error{
err: err,
Message: err.Error(),
Class: reflect.TypeOf(err).String(),
Stack: generateStack(autostack(err, stackOffset)),
}
}
func autostack(err error, offset int) []uintptr {
var s stacked
if errors.As(err, &s) {
return s.Callers()
}
stack := make([]uintptr, maxFrames)
length := runtime.Callers(2+offset, stack[:])
return stack[:length]
}
func generateStack(stack []uintptr) []*Frame {
frames := runtime.CallersFrames(stack)
result := make([]*Frame, 0, len(stack))
for {
frame, more := frames.Next()
result = append(result, &Frame{
File: frame.File,
Number: strconv.Itoa(frame.Line),
Method: frame.Function,
})
if !more {
break
}
}
return result
}