-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
370 lines (310 loc) · 8.72 KB
/
errors.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
// Package errors implements functions to deal with error handling.
package errors
import (
"fmt"
"reflect"
"regexp"
"runtime"
"strconv"
"strings"
"github.com/getsentry/sentry-go"
)
const _MAX_FRAMES = 100
var _ANSI_COLOR_PATTERN = regexp.MustCompile(`\x1b\[[0-9;]*m`)
type frame struct {
file string
line int
function string
}
// Error represents an error with traceback and additional info.
type Error struct {
kind string
module string
message string
cause error
extra map[string]any
stackTrace []frame
captureStackTrace bool
tags map[string]string
}
// New creates a new Error with a message (can have a format) and
// sets to optionally capture the stack trace when raised (default is true).
func New(message string, captureStackTrace ...bool) Error {
_captureStackTrace := true
if len(captureStackTrace) > 0 {
_captureStackTrace = captureStackTrace[0]
}
module := "unknown"
stackFrames := make([]uintptr, 1)
length := runtime.Callers(2, stackFrames)
if length > 0 {
frame, _ := runtime.CallersFrames(stackFrames[:length]).Next()
separator := strings.LastIndex(frame.Function, ".")
if separator >= 0 {
module = frame.Function[:separator]
}
}
return Error{
kind: message,
module: module,
message: message,
cause: nil,
extra: nil,
stackTrace: nil,
captureStackTrace: _captureStackTrace,
tags: nil,
}
}
// Raise creates a new Error instance formatting its message if
// needed and optionally captures its stack trace.
func (self Error) Raise(args ...any) *Error {
var stackTrace []frame
if self.captureStackTrace {
stackFrames := make([]uintptr, _MAX_FRAMES)
length := runtime.Callers(2, stackFrames)
if length > 0 {
stackTrace = make([]frame, 0, length)
cframes := runtime.CallersFrames(stackFrames[:length])
for {
cframe, more := cframes.Next()
stackTrace = append(stackTrace, frame{
file: cframe.File,
line: cframe.Line,
function: cframe.Function,
})
if !more {
break
}
}
}
}
return &Error{
kind: self.kind,
module: self.module,
message: fmt.Sprintf(self.message, args...),
cause: nil,
extra: make(map[string]any),
stackTrace: stackTrace,
captureStackTrace: self.captureStackTrace,
tags: make(map[string]string),
}
}
// Skip removes n frames of the raised Error.
func (self *Error) Skip(frames int) *Error {
if self.captureStackTrace {
self.stackTrace = self.stackTrace[frames:]
}
return self
}
// With adds more context to the raised Error's message.
func (self *Error) With(message string, args ...any) *Error {
self.message += ": " + fmt.Sprintf(message, args...)
return self
}
// Extra adds extra information to the raised Error.
func (self *Error) Extra(extra map[string]any) *Error {
for key, value := range extra {
self.extra[key] = value
}
return self
}
// Cause wraps an error into the raised Error.
func (self *Error) Cause(err error) *Error {
self.cause = err
return self
}
// Tags adds tags to the raised Error to further classify
// errors in services such as Sentry or New Relic.
func (self *Error) Tags(tags map[string]any) *Error {
for key, value := range tags {
self.tags[key] = fmt.Sprintf("%v", value)
}
return self
}
// Is compares whether an error is Error's type.
func (self Error) Is(err error) bool {
if err == nil {
return false
}
switch other := err.(type) {
case Error:
return self.kind == other.kind && self.module == other.module
case *Error:
return self.kind == other.kind && self.module == other.module
}
return false
}
// Has checks whether an error is wrapped inside the Error itself.
func (self Error) Has(err error) bool {
if self.Is(err) {
return true
}
if self.cause != nil {
switch cause := self.cause.(type) {
case Error:
return cause.Has(err)
case *Error:
return cause.Has(err)
default:
return err == cause || err.Error() == cause.Error()
}
}
return false
}
// In checks whether the Error itself is wrapped inside an error.
func (self Error) In(err error) bool {
switch err := err.(type) {
case Error:
return err.Has(self)
case *Error:
return err.Has(self)
default:
return false
}
}
// String implements the Stringer interface.
func (self Error) String() string {
causeMessage := ""
if self.cause != nil {
causeMessage = ": " + self.cause.Error()
}
return self.message + causeMessage
}
// Error implements the Error interface.
func (self Error) Error() string {
return self.String()
}
// MarshalText implements the TextMarshaler interface.
func (self Error) MarshalText() ([]byte, error) {
return []byte(self.String()), nil
}
// MarshalJSON implements the JSONMarshaler interface.
func (self Error) MarshalJSON() ([]byte, error) {
return []byte("\"" + self.String() + "\""), nil
}
// Format implements the Formatter interface:
// - %s: Error message
// - %v: First error report
// - %+v: All errors reports
// - default: Error message
func (self Error) Format(format fmt.State, verb rune) {
switch verb {
case 's':
format.Write([]byte(self.String()))
case 'v':
if format.Flag('+') {
format.Write([]byte(self.StringReport()))
} else {
format.Write([]byte(self.StringReport(false)))
}
default:
format.Write([]byte(self.String()))
}
}
func (self Error) stringReport(all bool, seenTraces map[string]bool) string {
report := ""
if len(self.stackTrace) > 0 {
ellipsis := false
for i := len(self.stackTrace) - 1; i >= 0; i-- {
fileline := self.stackTrace[i].file + ":" + strconv.Itoa(self.stackTrace[i].line)
_, seen := seenTraces[fileline]
if !seen {
seenTraces[fileline] = true
report += " " + fileline + "\n"
report += " " + self.stackTrace[i].function + "\n"
} else if !ellipsis {
ellipsis = true
report += " [...]\n"
}
}
} else {
report += " (Stack trace not available)\n"
}
report += "\x1b[0;31m" + self.message + "\x1b[0m\n"
if len(self.extra) > 0 {
report += " "
for key, value := range self.extra {
report += key + "=" + fmt.Sprintf("%v", value) + " "
}
report += "\n"
}
if all && self.cause != nil {
report += "\nCaused by the following error:\n"
switch cause := self.cause.(type) {
case Error:
report += cause.stringReport(all, seenTraces)
case *Error:
report += cause.stringReport(all, seenTraces)
default:
report += " (Stack trace not available)\n"
report += "\x1b[0;31m" + cause.Error() + "\x1b[0m (" +
strings.TrimPrefix(reflect.TypeOf(cause).String(), "*") + ")\n"
}
}
return report
}
// StringReport returns a string containing all the information about the first
// error (including the message, stack trace, extra...) or about all errors
// wrapped within the Error itself (default is all).
func (self Error) StringReport(all ...bool) string {
_all := true
if len(all) > 0 {
_all = all[0]
}
seenTraces := make(map[string]bool)
report := "\x1b[1;91m" + self.String() + "\x1b[0m\n\n"
report += "Traceback (most recent call last):\n"
report += self.stringReport(_all, seenTraces)
return report
}
func (self Error) sentryReport(report *sentry.Event) {
if self.cause != nil {
switch cause := self.cause.(type) {
case Error:
cause.sentryReport(report)
case *Error:
cause.sentryReport(report)
default:
report.Exception = append(report.Exception, sentry.Exception{
Type: strings.TrimPrefix(reflect.TypeOf(cause).String(), "*"),
Value: cause.Error(),
})
}
}
for key, value := range self.extra {
report.Extra[key] = value
}
for key, value := range self.tags {
report.Tags[key] = value
}
var stackTrace *sentry.Stacktrace
if len(self.stackTrace) > 0 {
stackTrace = &sentry.Stacktrace{
Frames: make([]sentry.Frame, 0, len(self.stackTrace)),
}
for i := len(self.stackTrace) - 1; i >= 0; i-- {
stackTrace.Frames = append(stackTrace.Frames, sentry.NewFrame(runtime.Frame{
Function: self.stackTrace[i].function,
File: self.stackTrace[i].file,
Line: self.stackTrace[i].line,
}))
}
}
report.Exception = append(report.Exception, sentry.Exception{
Type: self.kind,
Value: self.String(),
Module: self.module,
Stacktrace: stackTrace,
})
}
// SentryReport returns a Sentry Event containing all the information about the
// first error and all errors wrapped within itself (including the types, packages
// messages, stack traces, extra, tags...).
func (self Error) SentryReport() *sentry.Event {
report := sentry.NewEvent()
report.Level = sentry.LevelError
report.Message = _ANSI_COLOR_PATTERN.ReplaceAllString(self.StringReport(), "")
report.Tags["package"] = self.module
self.sentryReport(report)
return report
}