-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patherrors.go
90 lines (79 loc) · 1.92 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
package retry
import (
"errors"
"fmt"
"time"
)
// PermanentError signals that the operation should not be retried.
type PermanentError struct {
Err error
}
// Permanent wrap error with permanent error.
// If operation returns a permanent error, retries will be stopped.
func Permanent(err error) error {
if err == nil {
return nil
}
return PermanentError{Err: err}
}
func (e PermanentError) Error() string {
return e.Err.Error()
}
func (e PermanentError) Unwrap() error {
return e.Err
}
// Error wraps the original error and contains information about the last retry.
type Error struct {
LastDelay time.Duration
ElapsedTime time.Duration
Retries int
Msg string
Err error
}
func newError(err, ctxErr error, msg string, retries int, lastDelay time.Duration, elapsed time.Duration) error {
e := &Error{
ElapsedTime: elapsed,
Retries: retries,
LastDelay: lastDelay,
Err: err,
}
switch {
case ctxErr != nil && err == nil:
e.Msg = fmt.Sprintf("retrying %d canceled, time elapsed: %s, last delay: %s", retries, elapsed, lastDelay)
e.Err = ctxErr
case ctxErr != nil && err != nil:
e.Msg = fmt.Sprintf("retrying %d canceled: %s, time elapsed: %s, last delay: %s", retries, ctxErr.Error(), elapsed, lastDelay)
case ctxErr == nil && err != nil:
e.Msg = fmt.Sprintf("retrying %d stopped, time elapsed: %s, last delay: %s", retries, elapsed, lastDelay)
default:
return nil
}
if msg != "" {
e.Msg = msg + ": " + e.Msg
}
return e
}
func (e *Error) Error() string {
if e.Err == nil {
return e.Msg
}
return e.Msg + ": " + e.Err.Error()
}
func (e *Error) Unwrap() error {
return e.Err
}
// As returns retry Error that wrap an original operation error.
func As(err error) *Error {
e := &Error{}
if errors.As(err, &e) {
return e
}
return nil
}
// Unwrap returns an original operation error.
func Unwrap(err error) error {
if e := As(err); e != nil {
return e.Err
}
return err
}