-
Notifications
You must be signed in to change notification settings - Fork 0
/
error_caller.kit.go
82 lines (72 loc) · 1.52 KB
/
error_caller.kit.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
package errorpkg
import (
"fmt"
"runtime"
"strings"
)
var (
// DefaultStackTracerDepth 错误追踪最深层数
DefaultStackTracerDepth = 10
)
// Println 输出错误
func Println(err error) {
callers := Caller(err)
fmt.Println(strings.Join(callers, "\n"))
}
// stackTracer errors.StackTrace
type stackTracer interface {
StackTrace() StackTrace
}
// Stack 序列化调用者:file:line
func Stack(err error) (callers []string) {
trace, ok := err.(stackTracer)
if !ok {
pc, _, _, _ := runtime.Caller(1)
callers = []string{
fmt.Sprintf("%+v", Frame(pc)),
}
return callers
}
// stack trace
st := trace.StackTrace()
callers = make([]string, len(st))
for i := range st {
callers[i] = fmt.Sprintf("%+v", st[i])
}
return callers
}
// Caller 序列化调用者:file:line
func Caller(err error) (callers []string) {
trace, ok := err.(stackTracer)
if !ok {
pc, _, _, _ := runtime.Caller(1)
callers = []string{
fmt.Sprintf("%+v", Frame(pc)),
}
return callers
}
// stack trace
st := trace.StackTrace()
if len(st) > DefaultStackTracerDepth {
st = st[:DefaultStackTracerDepth]
}
callers = make([]string, len(st))
for i := range st {
callers[i] = fmt.Sprintf("%+v", st[i])
}
return callers
}
// CallerWithSkip 序列化调用者:file:line
func CallerWithSkip(err error, skip int) (callers []string) {
callers = Caller(err)
callCounter := len(callers)
switch callCounter {
case 0, 1:
return callers
default:
}
if skip >= callCounter {
return callers[callCounter-1:]
}
return callers[skip:]
}