-
Notifications
You must be signed in to change notification settings - Fork 0
/
apperror.go
82 lines (76 loc) · 2.04 KB
/
apperror.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
package apperror
import (
"fmt"
)
// As wraps an existing error into a Kind.
// Invalid Kind values are mapped to Unknown.
// If the kind is OK or the error is nil, the function will return nil.
//
//gocyclo:ignore
func As(kind Kind, err error) error {
if err == nil {
return nil
}
switch kind {
case OK:
return nil
case ValidationError:
return validationError{error: err}
case UnauthorizedError:
return unauthorizedError{error: err}
case ForbiddenError:
return forbiddenError{error: err}
case NotFoundError:
return notFoundError{error: err}
case ConflictError:
return conflictError{error: err}
case PreconditionFailedError:
return preconditionFailedError{error: err}
case TooManyRequestsError:
return tooManyRequestsError{error: err}
case TimeoutError:
return timeoutError{error: err}
default:
return unknownError{error: err}
}
}
// New creates an error of the specified Kind.
// Invalid Kind values are mapped to Unknown.
// If the kind is OK, the function will return nil.
func New(kind Kind, msg string, a ...any) error {
err := fmt.Errorf(msg, a...)
return As(kind, err)
}
// IsFinal returns true for error kinds that are not expected to change by
// merely repeating the operation.
//
// Note that this function exclusively considers error kinds, not the context
// in which they were produced. Not all operations can be repeated safely, and
// this function cannot provide guidance on making such a judgment.
func IsFinal(err error) bool {
switch kind := KindOf(err); kind {
case UnknownError,
TooManyRequestsError,
TimeoutError:
return false
default:
return true
}
}
// IsUser returns true for errors that are usually attributable to the user,
// as opposed to the implementation. For an analogy, think HTTP 400s
// (client errors) vs. HTTP 500s (server errors).
func IsUser(err error) bool {
switch kind := KindOf(err); kind {
case ValidationError,
UnauthorizedError,
ForbiddenError,
NotFoundError,
ConflictError,
PreconditionFailedError,
TooManyRequestsError:
return true
default:
return false
}
}