/
tracer.go
89 lines (78 loc) · 2.27 KB
/
tracer.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
package fj
import (
"fmt"
"runtime"
)
// stackTraceEntry はスタックトレースの構造体
type StackTraceEntry struct {
File string `json:"file"`
Line int `json:"line"`
Func string `json:"func"`
}
// StackTraceError はスタックトレースを含むエラー
type StackTraceError struct {
Message string `json:"message"`
StackTrace []StackTraceEntry `json:"stackTrace"`
}
// Error はエラーを文字列に変換する
func (e *StackTraceError) Error() string {
starckTraceStr := ""
for _, entry := range e.StackTrace {
starckTraceStr += fmt.Sprintf("File: %s, Line: %d, Func:%s\n", entry.File, entry.Line, entry.Func)
}
return fmt.Sprintf("%s\nStackTrace:\n%s", e.Message, starckTraceStr)
}
// 1. 新規のエラーを生成する NewStackTraceError("error message")
// 2. 既存のエラーにスタックトレースを追加する NewStackTraceError2(err, "")
// errorが既にスタックトレースを含んでいる場合は追加しない message = err.Error()
// NewStackTraceError はスタックトレースを含むエラーを生成する
func NewStackTraceError(msg string) error {
pc := make([]uintptr, 50)
n := runtime.Callers(2, pc) // runtimeとNewStackTraceErrorをスキップ
frames := runtime.CallersFrames(pc[:n])
var stackTrace []StackTraceEntry
for {
frame, more := frames.Next()
stackTrace = append(stackTrace, StackTraceEntry{
File: frame.File,
Line: frame.Line,
Func: frame.Function,
})
if !more {
break
}
}
return &StackTraceError{
Message: msg,
StackTrace: stackTrace,
}
}
// WrapError はエラーにスタックトレースを追加する
// NewStackTraceError で生成したエラーには追加できない
func WrapError(err error) error {
if err == nil {
return nil
}
if stErr, ok := err.(*StackTraceError); ok {
return stErr
}
pc := make([]uintptr, 50)
n := runtime.Callers(2, pc) // runtimeとNewStackTraceErrorをスキップ
frames := runtime.CallersFrames(pc[:n])
var stackTrace []StackTraceEntry
for {
frame, more := frames.Next()
stackTrace = append(stackTrace, StackTraceEntry{
File: frame.File,
Line: frame.Line,
Func: frame.Function,
})
if !more {
break
}
}
return &StackTraceError{
Message: err.Error(),
StackTrace: stackTrace,
}
}