-
Notifications
You must be signed in to change notification settings - Fork 50
/
error_canceled.go
66 lines (51 loc) · 1.47 KB
/
error_canceled.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
package exec
import (
"context"
"errors"
"github.com/hashicorp/go-multierror"
)
const RequestCanceledError = requestCanceledError("RequestCanceled")
type requestCanceledError string
func (e requestCanceledError) Error() string {
return string(e)
}
func CheckRequestCanceled(_ interface{}, err error) ErrorType {
if IsRequestCanceled(err) {
return ErrorTypePermanent
}
return ErrorTypeUnknown
}
type RequestCanceledCheck func(err error) bool
var requestCancelChecks = []RequestCanceledCheck{
isError(context.Canceled),
isError(context.DeadlineExceeded),
isError(RequestCanceledError),
}
func AddRequestCancelCheck(check RequestCanceledCheck) {
requestCancelChecks = append(requestCancelChecks, check)
}
// IsRequestCanceled checks if the given error was (only) caused by a canceled context - if there is any other error contained in it, we
// return false. Thus, if IsRequestCanceled returns true, you can (and should) ignore the error and stop processing instead.
func IsRequestCanceled(err error) bool {
multiErr := &multierror.Error{}
if errors.As(err, &multiErr) {
// check if one of the errors is no request canceled
for _, err := range multiErr.Errors {
if !IsRequestCanceled(err) {
return false
}
}
return len(multiErr.Errors) > 0
}
for _, check := range requestCancelChecks {
if check(err) {
return true
}
}
return false
}
func isError(target error) RequestCanceledCheck {
return func(err error) bool {
return errors.Is(err, target)
}
}