-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherror.go
392 lines (326 loc) · 7.87 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
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
package errors
import (
"bytes"
"encoding/json"
std "errors"
"fmt"
"strconv"
"strings"
"sync"
)
// ExtraField name of the extra error field.
type ExtraField string
// ExtraFields set of the extra error fields.
type ExtraFields map[ExtraField]interface{}
var _ error = &Error{}
// Error implements error interface.
type Error struct {
// errs list of combined errors. Used for Is and As methods.
errs []error
// formats list of formats and arguments to display error text.
// Used for Error and WithPrinter methods. len(errs) == len(formats).
formats []FormatArgs
// callers stack of function calls.
callers []uintptr
ReasonType ReasonType
ExtraFields
}
var (
delimiter = []byte("; ")
bufPool = sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
)
// Error implements error interface.
func (e *Error) Error() (s string) {
buf, _ := bufPool.Get().(*bytes.Buffer)
defer bufPool.Put(buf)
buf.Reset()
for i, f := range e.formats {
if i > 0 {
buf.Write(delimiter)
}
_, _ = f.WriteTo(buf)
}
return buf.String()
}
// Wrap wraps an error with a given message.
// err = errors.Wrap(err, "reading config")
// If you need to collect a stack when wrapping, set the Builder's parameter
// NeedStack (see Builder).
// If you need to panic when using bad error handling style, set Builder
// parameter PanicAboutBadStyle (see Builder).
func Wrap(err error, msg string) error {
return global.WithSkip(1).Wrap(err, msg)
}
func (b Builder) Wrap(err error, msg string) error {
if messageChecker != nil {
messageChecker(msg)
}
r := b.extractFrom(err)
if r == nil {
return nil
}
r.formats[0] = FormatArgs{
Format: "%v: %v",
Args: []interface{}{
FormatArgs{Format: msg},
r.formats[0],
},
}
if b.NeedStack {
r.callers = b.CallersIfNeed()
}
return r
}
// WithMessage for compatibility with https://github.com/pkg/errors.
func WithMessage(err error, msg string) error {
return global.WithoutStack().Wrap(err, msg)
}
// WithMessagef for compatibility with https://github.com/pkg/errors.
func WithMessagef(err error, msg string, args ...interface{}) error {
return global.WithoutStack().Wrapf(err, msg, args...)
}
// Wrapf wraps an error with a given message and arguments, like Printf functions.
// err = errors.Wrapf(
// err, "reading config %q", path,
// )
// If you need to collect a stack when wrapping, set the Builder's parameter
// NeedStack (see Builder).
// If you need to panic when using bad error handling style, set Builder parameter
// PanicAboutBadStyle (see Builder).
func Wrapf(err error, msg string, args ...interface{}) error {
return global.WithSkip(1).Wrapf(err, msg, args...)
}
func (b Builder) Wrapf(err error, format string, args ...interface{}) error {
if messageChecker != nil {
messageChecker(format)
}
if formatChecker != nil {
formatChecker(format, args...)
}
r := b.extractFrom(err)
if r == nil {
return nil
}
r.formats[0] = FormatArgs{
Format: "%v: %v",
Args: []interface{}{
FormatArgs{Format: format, Args: args},
r.formats[0],
},
}
if b.NeedStack {
r.callers = b.CallersIfNeed()
}
return r
}
// WithExtraFields sets extra error fields to err.
// err = WithExtraFields(
// err, ExtraFields{
// "SQLQuery": query,
// "SQLArgs": args,
// },
// )
func WithExtraFields(err error, fields ExtraFields) error {
return global.WithSkip(1).WithExtraFields(err, fields)
}
func (b Builder) WithExtraFields(err error, fields ExtraFields) error {
r := b.extractFrom(err)
if r == nil {
return nil
}
for field, value := range fields {
r.ExtraFields[field] = value
}
if len(r.callers) == 0 {
r.callers = b.CallersIfNeed()
}
return r
}
// GetValue returns the value of the extra field from
// the error, if present.
func GetValue(err error, key ExtraField) (interface{}, bool) {
var target *Error
if !std.As(err, &target) {
return nil, false
}
field, exist := target.ExtraFields[key]
return field, exist
}
// Cause compatibility with https://github.com/pkg/errors Cause()
// causeErr = Cause(err)
// if causeErr != nil {
// // cause handling ...
// }
func Cause(err error) error {
type causer interface {
Cause() error
}
for err != nil {
cause, ok := err.(causer)
if !ok {
break
}
err = cause.Cause()
}
return err
}
// Cause implements causer interface for compatibility with
// https://github.com/pkg/errors Cause()
// causeErr = Cause(err)
// if causeErr != nil {
// // cause handling ...
// }
func (e *Error) Cause() error {
if len(e.errs) == 0 {
return nil
}
return Cause(e.errs[0])
}
// extractFrom returns an Error pointer containing
// a copy of the data from err. Special cases:
// return nil if:
// - err == nil
// - errors.As(err, *Error) && len(Error.errs) == 0
// return new pointer to Error if:
// - !errors.As(err, *Error)
// return new pointer to copy of Error if:
// - errors.As(err, *Error) && len(Error.errs) > 0.
func (b Builder) extractFrom(err error) (r *Error) {
if err == nil {
return nil
}
if std.As(err, &r) {
if len(r.errs) == 0 {
return nil
}
// Avoiding data races.
extraFields := make(ExtraFields, len(r.ExtraFields))
for key, v := range r.ExtraFields {
extraFields[key] = v
}
formats := make([]FormatArgs, len(r.formats))
copy(formats, r.formats)
r = &Error{
errs: r.errs,
formats: formats,
callers: r.callers,
ReasonType: r.ReasonType,
ExtraFields: extraFields,
}
if b.OverwriteReason {
r.ReasonType = b.ReasonType
}
return r
}
errs := []error{err}
if m, ok := err.(MultiError); ok {
errs = m.Errors()
}
formats := make([]FormatArgs, len(errs))
var n int
for _, err := range errs {
if err == nil {
continue
}
errs[n], formats[n] = err, FormatArgs{
Format: "%v",
Args: []interface{}{err},
}
n++
}
errs, formats = errs[:n], formats[:n]
if len(errs) == 0 {
return nil
}
return &Error{
errs: errs,
formats: formats,
ExtraFields: map[ExtraField]interface{}{},
ReasonType: b.ReasonType,
}
}
var (
// flags available flags for fmt.Formatter.
flags = [...]int{
'#', '+', ' ', '-', '0',
}
)
// Formatter controls how fmt.State and rune
// are interpreted, and may call fmt.Sprint(f)
// or fmt.Fprint(f) etc. to generate its output.
type Formatter func(e *Error, f fmt.State, verb rune)
// customFormatter if present, called when the
// method (*Error) Error() is called.
var customFormatter Formatter
// SetCustomFormatter sets a global Formatter for
// custom error display. Unsafe for concurrent use.
func SetCustomFormatter(f Formatter) {
customFormatter = f
}
// Format implements fmt.Formatter.
func (e *Error) Format(f fmt.State, verb rune) {
if customFormatter != nil {
customFormatter(e, f, verb)
return
}
var format strings.Builder
format.Grow(20)
format.WriteByte('%')
var useJSON, useIndent bool
for _, flag := range flags {
if verb == 'v' && !useJSON {
switch flag {
case '#', '+':
useJSON = f.Flag(flag)
continue
}
}
if useJSON && flag == ' ' {
useIndent = f.Flag(flag)
continue
}
if f.Flag(flag) {
format.WriteByte(byte(flag))
}
}
// Remove alignment for json indented.
if !useIndent {
width, ok := f.Width()
if ok {
format.WriteString(strconv.Itoa(width))
}
prec, ok := f.Precision()
if ok {
format.WriteByte('.')
format.WriteString(strconv.Itoa(prec))
}
}
format.WriteRune(verb)
if !useJSON {
_, _ = fmt.Fprintf(f, format.String(), e.Error())
return
}
buf, _ := bufPool.Get().(*bytes.Buffer)
defer bufPool.Put(buf)
buf.Reset()
encoder := json.NewEncoder(buf)
if useIndent {
encoder.SetIndent("", " ")
}
v := make(map[string]interface{}, 3)
v["Error"] = e.Error()
if len(e.ExtraFields) > 0 {
v["Extra"] = e.ExtraFields
}
if len(e.callers) > 0 && f.Flag('#') {
v["Stack"] = e.StackTrace().ToStrings()
}
_ = encoder.Encode(v)
// Remove carriage return.
buf.Truncate(buf.Len() - 1)
_, _ = fmt.Fprintf(f, format.String(), buf.String())
}