-
Notifications
You must be signed in to change notification settings - Fork 40
/
errors.go
504 lines (429 loc) · 9.23 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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
/*
* Copyright 2022 ICON Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Package errors is replacement package for standard errors package.
// It attaches error code and stack information to the error object.
package errors
import (
serrors "errors"
"fmt"
"io"
"reflect"
"runtime"
"github.com/pkg/errors"
)
type Code int
const CodeSegment = 1000
const (
CodeSCORE Code = iota * CodeSegment
CodeGeneral
CodeService
CodeConsensus
CodeNetwork
CodeBlock
CodeServer
CodeCritical
)
const (
Success Code = 0
UnknownError Code = CodeGeneral + iota
IllegalArgumentError
UnsupportedError
InvalidStateError
NotFoundError
InvalidNetworkError
TimeoutError
ExecutionFailError
InterruptedError
)
var (
ErrUnknown = NewBase(UnknownError, "UnknownError")
ErrIllegalArgument = NewBase(IllegalArgumentError, "IllegalArgument")
ErrInvalidState = NewBase(InvalidStateError, "InvalidState")
ErrUnsupported = NewBase(UnsupportedError, "Unsupported")
ErrNotFound = NewBase(NotFoundError, "NotFound")
ErrInvalidNetwork = NewBase(InvalidNetworkError, "InvalidNetwork")
ErrTimeout = NewBase(TimeoutError, "Timeout")
ErrExecutionFail = NewBase(ExecutionFailError, "ExecutionFail")
ErrInterrupted = NewBase(InterruptedError, "Interrupted")
)
const (
CriticalUnknownError = CodeCritical + iota
CriticalIOError
CriticalFormatError
CriticalHashError
CriticalRerunError
)
func IsCriticalCode(c Code) bool {
return c >= CodeCritical && c < CodeCritical+CodeSegment
}
func IsCritical(e error) bool {
return IsCriticalCode(CodeOf(e))
}
func (c Code) New(msg string) error {
return Errorc(c, msg)
}
func (c Code) Errorf(f string, args ...interface{}) error {
return Errorcf(c, f, args...)
}
func (c Code) Wrap(e error, msg string) error {
return Wrapc(e, c, msg)
}
func (c Code) Wrapf(e error, f string, args ...interface{}) error {
return Wrapcf(e, c, f, args...)
}
func (c Code) AttachTo(e error) error {
return WithCode(e, c)
}
func (c Code) Equals(e error) bool {
return CodeOf(e) == c
}
// New makes an error including a stack without any code
// If you want to make base error without stack
type stack []uintptr
func (s *stack) StackTrace() errors.StackTrace {
f := make([]errors.Frame, len(*s))
for i := 0; i < len(f); i++ {
f[i] = errors.Frame((*s)[i])
}
return f
}
func callers(skip int) *stack {
const depth = 16
var pcs [depth]uintptr
n := runtime.Callers(skip, pcs[:])
var st stack = pcs[0:n]
return &st
}
type withStack struct {
error
*stack
}
func (e *withStack) Format(f fmt.State, c rune) {
formatError(e, f, c)
}
func (e *withStack) Unwrap() error {
return Unwrap(e.error)
}
func New(msg string) error {
return &withStack{
error: serrors.New(msg),
stack: callers(3),
}
}
func Errorf(f string, args ...interface{}) error {
return &withStack{
error: fmt.Errorf(f, args...),
stack: callers(3),
}
}
type wrappedWithStack struct {
wrapped
*stack
}
func (e *wrappedWithStack) Format(f fmt.State, c rune) {
formatError(e, f, c)
}
func WithStack(e error) error {
if e == nil {
return nil
}
return &wrappedWithStack{
wrapped: wrap(e),
stack: callers(3),
}
}
/*------------------------------------------------------------------------------
Base error only with message and code
For general usage, you may return this directly.
*/
func formatError(e error, f fmt.State, c rune) {
for {
e = formatErrorOne(e, f, c)
if e == nil {
return
}
io.WriteString(f, "\nWrapping ")
}
}
func formatErrorOne(e error, f fmt.State, c rune) error {
switch c {
case 's':
io.WriteString(f, e.Error())
case 'q':
fmt.Fprintf(f, "%q", e.Error())
case 'v':
if coder, ok := CoderOf(e); ok {
fmt.Fprintf(f, "E%04d:%s", coder.ErrorCode(), e.Error())
} else {
io.WriteString(f, e.Error())
}
if f.Flag('+') {
if tracer, ok := StackTracerOf(e); ok {
tracer.StackTrace().Format(f, c)
return Unwrap(tracer.(ErrorWithStack))
} else {
return Unwrap(e)
}
}
}
return nil
}
type code int
func (c code) ErrorCode() Code {
return Code(c)
}
type message string
func (e message) Error() string {
return string(e)
}
type codedError struct {
code
message
}
func (e *codedError) Format(f fmt.State, c rune) {
formatError(e, f, c)
}
func NewBase(c Code, msg string) *codedError {
return &codedError{code(c), message(msg)}
}
/*------------------------------------------------------------------------------
Coded error object
*/
type withCodeAndStack struct {
error
code
*stack
}
func (e *withCodeAndStack) Format(f fmt.State, c rune) {
formatError(e, f, c)
}
func (e *withCodeAndStack) Unwrap() error {
return Unwrap(e.error)
}
func Errorc(c Code, msg string) error {
return &withCodeAndStack{
error: serrors.New(msg),
code: code(c),
stack: callers(3),
}
}
func Errorcf(c Code, f string, args ...interface{}) error {
return &withCodeAndStack{
error: fmt.Errorf(f, args...),
code: code(c),
stack: callers(3),
}
}
type wrappedWithCode struct {
wrapped
code
}
func (e *wrappedWithCode) Format(f fmt.State, c rune) {
formatError(e, f, c)
}
func WithCode(err error, c Code) error {
if err == nil {
return nil
}
return &wrappedWithCode{
wrapped: wrap(err),
code: code(c),
}
}
type wrapped struct {
error
}
func (e *wrapped) Unwrap() error {
return e.error
}
func wrap(e error) wrapped {
return wrapped{e}
}
type wrappedWithMessage struct {
wrapped
message
*stack
}
func (e *wrappedWithMessage) Format(f fmt.State, c rune) {
formatError(e, f, c)
}
func Wrap(e error, msg string) error {
if e == nil {
return nil
}
return &wrappedWithMessage{
wrapped: wrap(e),
message: message(msg),
stack: callers(3),
}
}
func Wrapf(e error, f string, args ...interface{}) error {
if e == nil {
return nil
}
return &wrappedWithMessage{
wrapped: wrap(e),
message: message(fmt.Sprintf(f, args...)),
stack: callers(3),
}
}
type wrappedWithCodeMessage struct {
wrapped
code
message
*stack
}
func (e *wrappedWithCodeMessage) Format(f fmt.State, c rune) {
formatError(e, f, c)
}
func Wrapc(e error, c Code, msg string) error {
if e == nil {
return nil
}
return &wrappedWithCodeMessage{
wrapped: wrap(e),
code: code(c),
message: message(msg),
stack: callers(3),
}
}
func Wrapcf(e error, c Code, f string, args ...interface{}) error {
if e == nil {
return nil
}
return &wrappedWithCodeMessage{
wrapped: wrap(e),
code: code(c),
message: message(fmt.Sprintf(f, args...)),
stack: callers(3),
}
}
type ErrorCoder interface {
error
ErrorCode() Code
}
func CoderOf(e error) (ErrorCoder, bool) {
coder := FindCause(e, func(err error) bool {
_, ok := err.(ErrorCoder)
return ok
})
if coder != nil {
return coder.(ErrorCoder), true
} else {
return nil, false
}
}
func CodeOf(e error) Code {
if e == nil {
return Success
}
if coder, ok := CoderOf(e); ok {
return coder.ErrorCode()
}
return UnknownError
}
type StackTracer interface {
StackTrace() errors.StackTrace
}
type ErrorWithStack interface {
error
StackTracer
}
func StackTracerOf(e error) (StackTracer, bool) {
tr := FindCause(e, func(err error) bool {
_, ok := err.(StackTracer)
return ok
})
if tr != nil {
return tr.(StackTracer), true
}
return nil, false
}
// Unwrapper is interface to unwrap the error to get the origin error.
type Unwrapper interface {
Unwrap() error
}
func Unwrap(err error) error {
switch obj := err.(type) {
case interface{ Unwrap() error }:
return obj.Unwrap()
case interface{ Cause() error }:
return obj.Cause()
default:
return nil
}
}
// Is checks whether err is caused by the target.
func Is(err, target error) bool {
if target == nil {
return err == target
}
isComparable := reflect.TypeOf(target).Comparable()
for {
if isComparable && err == target {
return true
}
if x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {
return true
}
if err = Unwrap(err); err == nil {
return false
}
}
}
func FindCause(err error, cb func(err error) bool) error {
for {
if err == nil {
return nil
}
if cb(err) {
return err
}
err = Unwrap(err)
}
}
func ToString(e error) string {
if e == nil {
return ""
} else {
return fmt.Sprintf("%v", e)
}
}
type withFormat struct {
error
}
func (e *withFormat) Unwrap() error {
return Unwrap(e.error)
}
func (e *withFormat) Format(f fmt.State, c rune) {
formatError(e.error, f, c)
}
func (e *withFormat) String() string {
return e.error.Error()
}
// Error returns wrapped error providing formatter to show error code
// and stacks properly.
func Error(e error) error {
if e == nil {
return nil
}
switch obj := e.(type) {
case *withStack, *wrappedWithCodeMessage, *codedError, *withCodeAndStack, *wrappedWithCode, *wrappedWithMessage, *wrappedWithStack, *withFormat:
return obj
default:
return &withFormat{e}
}
}