-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy patherrors.go
403 lines (340 loc) · 11.7 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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
package weberr
import (
goerrors "errors"
"fmt"
"net/http"
"github.com/pkg/errors"
)
// ErrorType is the type of an error
type ErrorType uint
const (
// NoType error - Default placeholder for un-typed errors.
// Methods on NoType behave differently than other types - they
// will preserve an existing type when wrapping a typed error.
NoType ErrorType = iota
// 4xx Client errors
// -----------------
// BadRequest error - Code 400
BadRequest ErrorType = http.StatusBadRequest
// Unauthorized error - Code 401
Unauthorized ErrorType = http.StatusUnauthorized
// PaymentRequired error - Code 402
PaymentRequired ErrorType = http.StatusPaymentRequired
// Forbidden error - Code 403
Forbidden ErrorType = http.StatusForbidden
// NotFound error - Code 404
NotFound ErrorType = http.StatusNotFound
// MethodNotAllowed error - Code 405
MethodNotAllowed ErrorType = http.StatusMethodNotAllowed
// NotAcceptable error - Code 406
NotAcceptable ErrorType = http.StatusNotAcceptable
// ProxyAuthRequired error - Code 407
ProxyAuthRequired ErrorType = http.StatusProxyAuthRequired
// RequestTimeout error - Code 408
RequestTimeout ErrorType = http.StatusRequestTimeout
// Conflict error - Code 409
Conflict ErrorType = http.StatusConflict
// Gone error - Code 410
Gone ErrorType = http.StatusGone
// LengthRequired error - Code 411
LengthRequired ErrorType = http.StatusLengthRequired
// PreconditionFailed error - Code 412
PreconditionFailed ErrorType = http.StatusPreconditionFailed
// RequestEntityTooLarge error - Code 413
RequestEntityTooLarge ErrorType = http.StatusRequestEntityTooLarge
// RequestURITooLong error - Code 414
RequestURITooLong ErrorType = http.StatusRequestURITooLong
// UnsupportedMediaType error - Code 415
UnsupportedMediaType ErrorType = http.StatusUnsupportedMediaType
// RequestedRangeNotSatisfiable error - Code 416
RequestedRangeNotSatisfiable ErrorType = http.StatusRequestedRangeNotSatisfiable
// ExpectationFailed error - Code 417
ExpectationFailed ErrorType = http.StatusExpectationFailed
// Teapot error - Code 418
Teapot ErrorType = http.StatusTeapot
// UnprocessableEntity error - Code 422
UnprocessableEntity ErrorType = http.StatusUnprocessableEntity
// Locked error - Code 423
Locked ErrorType = http.StatusLocked
// FailedDependency error - Code 424
FailedDependency ErrorType = http.StatusFailedDependency
// UpgradeRequired error - Code 426
UpgradeRequired ErrorType = http.StatusUpgradeRequired
// PreconditionRequired error - Code 428
PreconditionRequired ErrorType = http.StatusPreconditionRequired
// TooManyRequests error - Code 429
TooManyRequests ErrorType = http.StatusTooManyRequests
// RequestHeaderFieldsTooLarge error - Code 431
RequestHeaderFieldsTooLarge ErrorType = http.StatusRequestHeaderFieldsTooLarge
// UnavailableForLegalReasons error - Code 451
UnavailableForLegalReasons ErrorType = http.StatusUnavailableForLegalReasons
// 5xx Server errors
// -----------------
// InternalServerError error - Code 500
InternalServerError ErrorType = http.StatusInternalServerError
// NotImplemented error - Code 501
NotImplemented ErrorType = http.StatusNotImplemented
// BadGateway error - Code 502
BadGateway ErrorType = http.StatusBadGateway
// ServiceUnavailable error - Code 503
ServiceUnavailable ErrorType = http.StatusServiceUnavailable
// GatewayTimeout error - Code 504
GatewayTimeout ErrorType = http.StatusGatewayTimeout
// HTTPVersionNotSupported error - Code 505
HTTPVersionNotSupported ErrorType = http.StatusHTTPVersionNotSupported
// VariantAlsoNegotiates error - Code 506
VariantAlsoNegotiates ErrorType = http.StatusVariantAlsoNegotiates
// InsufficientStorage error - Code 507
InsufficientStorage ErrorType = http.StatusInsufficientStorage
// LoopDetected error - Code 508
LoopDetected ErrorType = http.StatusLoopDetected
// NotExtended error - Code 510
NotExtended ErrorType = http.StatusNotExtended
// NetworkAuthenticationRequired error - Code 511
NetworkAuthenticationRequired ErrorType = http.StatusNetworkAuthenticationRequired
)
// customError wraps an error with type, separate user message, and details.
type customError struct {
error
errorType ErrorType
userMessage string
details []interface{}
}
// causer interface allows unwrapping an error.
// causer is also used in github.com/pkg/errors
type causer interface {
Cause() error
}
// Cause unwraps error
func (c *customError) Cause() error { return c.error }
// typed interface identifies error with a type
type typed interface {
Type() ErrorType
}
// Type returns the error type
func (c *customError) Type() ErrorType { return c.errorType }
// GetType returns the error type for all errors.
// If error is not `typed` - it returns NoType.
func GetType(err error) ErrorType {
if typeErr, ok := err.(typed); ok {
return typeErr.Type()
}
return NoType
}
// userMessager identifies an error with a user message
type userMessager interface {
UserMessage() string
}
// UserMessage returns the user message
func (c *customError) UserMessage() string { return c.userMessage }
// GetUserMessage returns user readable error message for all errors.
// If error is not `userMessager` returns empty string.
func GetUserMessage(err error) string {
if msgErr, ok := err.(userMessager); ok {
return msgErr.UserMessage()
}
return ""
}
// errorDetailer identifies an error with details
type errorDetailer interface {
Details() []interface{}
}
// Details returns the error details
func (c *customError) Details() []interface{} { return c.details }
// GetDetails returns a slice of arbitrary details for all errors.
// If error is not `errorDetailer` returns nil.
func GetDetails(err error) []interface{} {
if detailedError, ok := err.(errorDetailer); ok {
return detailedError.Details()
}
return nil
}
// Errorf creates a new error of this type with formatted string.
func (errorType ErrorType) Errorf(msg string, args ...interface{}) error {
return &customError{
error: errors.WithStack(errors.Errorf(msg, args...)),
errorType: errorType,
}
}
// Wrapf creates a wrapping error of this type, with formatted string.
// The relation to the wrapped err is implicit, do not add a %s for it (like you would with fmt.Errorf).
// If wrapped err is nil, still returns a new error.
func (errorType ErrorType) Wrapf(err error, msg string, args ...interface{}) error {
if err == nil {
return errorType.Errorf(msg, args...)
}
c := new(customError)
c.error = errors.Wrapf(err, msg, args...)
c.userMessage = GetUserMessage(err)
c.details = GetDetails(err)
if errorType != NoType {
c.errorType = errorType
} else {
c.errorType = GetType(err)
}
return c
}
// UserWrapf adds a formatted user readable message to an error.
// If wrapped err already had a user message, combines them with a colon, you should not add a %s for it.
// Also sets error type (or preserves existing type if called on NoType).
// If wrapped err is nil, still returns a new error.
func (errorType ErrorType) UserWrapf(err error, msg string, args ...interface{}) error {
if err == nil {
return errorType.UserErrorf(msg, args...)
}
userMsg := fmt.Sprintf(msg, args...)
c := new(customError)
c.error = errors.WithStack(err)
c.details = GetDetails(err)
origMsg := GetUserMessage(err)
if origMsg != "" {
userMsg = fmt.Sprintf("%s: %s", userMsg, origMsg)
}
c.userMessage = userMsg
if errorType != NoType {
c.errorType = errorType
} else {
c.errorType = GetType(err)
}
return c
}
// UserErrorf creates a new error with a user readable message.
func (errorType ErrorType) UserErrorf(msg string, args ...interface{}) error {
message := fmt.Sprintf(msg, args...)
return &customError{
error: errors.WithStack(errors.New(message)),
errorType: errorType,
userMessage: message,
}
}
// AddDetails adds a details element to an error.
// Also sets error type (or preserves existing type if called on NoType).
func (errorType ErrorType) AddDetails(err error, details interface{}) error {
if details == nil {
return err
}
if err == nil {
return errorType.details(details)
}
c := new(customError)
c.error = errors.WithStack(err)
c.userMessage = GetUserMessage(err)
c.details = append(GetDetails(err), details)
if errorType != NoType {
c.errorType = errorType
} else {
c.errorType = GetType(err)
}
return c
}
// details creates a new error with arbitrary details
func (errorType ErrorType) details(details interface{}) error {
return &customError{
error: errors.WithStack(errors.New("")),
errorType: errorType,
details: []interface{}{details},
}
}
// Set the type of the error
func (errorType ErrorType) Set(err error) error {
if err == nil {
return nil
}
return &customError{
error: errors.WithStack(err),
errorType: errorType,
userMessage: GetUserMessage(err),
details: GetDetails(err),
}
}
func (errorType ErrorType) SetUserMessage(err error, msg string) error {
if err == nil {
return nil
}
var newType ErrorType
if errorType != NoType {
newType = errorType
} else {
newType = GetType(err)
}
return &customError{
error: errors.WithStack(err),
errorType: newType,
userMessage: msg,
details: GetDetails(err),
}
}
// Errorf returns a new NoType error with formatted string.
func Errorf(msg string, args ...interface{}) error {
return NoType.Errorf(msg, args...)
}
// Wrapf creates a wrapping error, with unmodified type and formatted string.
// The relation to the wrapped err is implicit, do not add a %s for it (like you would with fmt.Errorf).
// If wrapped err is nil, still returns a new error.
func Wrapf(err error, msg string, args ...interface{}) error {
return NoType.Wrapf(err, msg, args...)
}
// UserErrorf returns an error with formatted user message.
func UserErrorf(msg string, args ...interface{}) error {
return NoType.UserErrorf(msg, args...)
}
// UserWrapf adds a user readable message to an error.
func UserWrapf(err error, msg string, args ...interface{}) error {
return NoType.UserWrapf(err, msg, args...)
}
// AddDetails adds arbitrary details to an error.
func AddDetails(err error, details interface{}) error {
return NoType.AddDetails(err, details)
}
// SetUserMessage sets the user message to an error
func SetUserMessage(err error, msg string) error {
return NoType.SetUserMessage(err, msg)
}
// stackTracer interface is internally defined in github.com/pkg/errors
// and identifies an error with a stack trace
type stackTracer interface {
StackTrace() errors.StackTrace
}
// baseStackTracer is a helper function to allow reaching
// the initial wrapper that has a stack trace
func baseStackTracer(err error) error {
if cause, ok := err.(causer); ok {
candidate := baseStackTracer(cause.Cause())
if candidate != nil {
return candidate
}
if _, ok := err.(stackTracer); ok {
return err
}
}
return nil
}
// GetStackTrace returns the stack trace starting from the first error
// that has been wrapped / created
func GetStackTrace(err error) string {
if err == nil {
return ""
}
err = baseStackTracer(err)
x, ok := err.(stackTracer)
if !ok {
// The error doesn't have a stack trace attached to it
return fmt.Sprintf("%+v", err)
}
st := x.StackTrace()
return fmt.Sprintf("%+v\n", st[1:])
}
// As finds the first error in err's chain that matches target,
// and if so, sets target to that error value and returns true. Otherwise, it returns false.
func As(err error, target interface{}) bool {
return goerrors.As(err, target)
}
// Is finds the first error in err's chain that matches target,
// and if so, sets target to that error value and returns true. Otherwise, it returns false.
func Is(err error, target error) bool {
return goerrors.Is(err, target)
}
// Join returns an error that wraps the given errors into one.
func Join(errs ...error) error {
return goerrors.Join(errs...)
}