-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjerror.go
225 lines (186 loc) · 4.45 KB
/
jerror.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/*
Package jerror is a helper to create errors. It supports creating parametrized
messages to give more information on the error and easier way of wrapping.
These errors are compatible with standard errors.Is and errors.Unwrap.
More information at http://github.com/jfontan/jerror
Example:
ErrCannotOpen := jerror.New("can not open file %s")
fileName := "file.txt"
err := os.Open(fileName)
if err != nil {
return ErrCannotOpen.New().Args(fileName).Wrap(err)
}
*/
package jerror
import (
"fmt"
"log/slog"
"runtime"
"sort"
"strconv"
"time"
"golang.org/x/exp/maps"
)
var _ error = &JError{}
const (
debug = false
stackDepth = 10
stackSkip = 4
)
// New creates a new Error with the given message.
func New(message string) *JError {
err := &JError{
instance: false,
message: message,
}
return err
}
// JError contains an error with a message and a unique identifier.
type JError struct {
instance bool
message string
parent error
wrap error
values map[string]interface{}
frames []Frame
}
// Frame is a stack frame for the error.
type Frame struct {
Function string
File string
Line int
}
// New creates a new Error instance and fills the stack trace.
func (j *JError) New() *JError {
return j.newStack(stackSkip)
}
func (j *JError) newStack(stackSkip int) *JError {
return &JError{
instance: true,
message: j.message,
parent: j,
frames: fillFrames(stackSkip, stackDepth),
values: make(map[string]interface{}),
}
}
func (j *JError) get() *JError {
if j.instance {
return j
}
return j.newStack(stackSkip + 1)
}
// Args returns a version of the error with the parameters from the message
// substituted by its args.
func (j *JError) Args(args ...interface{}) *JError {
j = j.get()
j.message = fmt.Sprintf(j.message, args...)
return j
}
// Wrap returns a version of the error wrapping another error.
func (j *JError) Wrap(err error) *JError {
j = j.get()
j.wrap = err
return j
}
// Error implements error interface.
func (j *JError) Error() string {
wmesg := ""
if j.wrap != nil {
wmesg = ": " + j.wrap.Error()
}
return j.message + wmesg
}
// Unwrap implements error interface.
func (j *JError) Unwrap() error {
return j.wrap
}
// Is implements error interface.
func (j *JError) Is(err error) bool {
if jerr, ok := err.(*JError); ok {
return jerr == j.parent || jerr.parent == j.parent
}
return false
}
// Set sets a value in the error.
func (j *JError) Set(key string, value interface{}) *JError {
j = j.get()
j.values[key] = value
return j
}
// Get returns a value from the error.
func (j *JError) Get(key string) (interface{}, bool) {
val, ok := j.values[key]
return val, ok
}
// GetString returns a string value from the error.
func (j *JError) GetString(key string) (string, bool) {
val, ok := j.values[key].(string)
return val, ok
}
// GetInt returns an int value from the error.
func (j *JError) GetInt(key string) (int, bool) {
val, ok := j.values[key].(int)
return val, ok
}
// Frames returns the stack frames of the error.
func (j *JError) Frames() []Frame {
return j.frames
}
func (j *JError) SlogAttributes(group string, error bool) slog.Attr {
var attrs []any
if error {
attrs = append(attrs, slog.String("error", j.Error()))
}
if len(j.frames) > 0 {
var lines []any
for i, frame := range j.frames {
lines = append(lines, slog.String(strconv.Itoa(i), fmt.Sprintf(
"%s %s:%d",
frame.Function,
frame.File,
frame.Line,
)))
}
attrs = append(attrs, slog.Group("stack", lines...))
}
// TODO: do not convert values to string
if len(j.values) > 0 {
var values []any
keys := maps.Keys(j.values)
sort.Strings(keys)
for _, key := range keys {
value := j.values[key]
values = append(values, slog.String(key, fmt.Sprintf("%v", value)))
}
attrs = append(attrs, slog.Group("values", values...))
}
last := Last(j)
if last != nil && last != j {
attrs = append(attrs, last.SlogAttributes("last_jerror", true))
}
return slog.Group(group, attrs...)
}
func fillFrames(skip, depth int) []Frame {
if debug {
start := time.Now()
defer func() {
fmt.Printf("fillFrames took %v\n", time.Since(start).String())
}()
}
pc := make([]uintptr, depth)
num := runtime.Callers(skip, pc)
callerFrames := runtime.CallersFrames(pc[:num])
var frames []Frame
for {
frame, more := callerFrames.Next()
frames = append(frames, Frame{
Function: frame.Function,
File: frame.File,
Line: frame.Line,
})
if !more {
break
}
}
return frames
}