-
Notifications
You must be signed in to change notification settings - Fork 8
/
errors.go
98 lines (83 loc) · 1.81 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
package allsrv
import (
"errors"
)
const (
errTypeUnknown = iota
errTypeExists
errTypeInvalid
errTypeNotFound
errTypeUnAuthed
errTypeInternal
)
var errTypeStrs = [...]string{
errTypeUnknown: "unknown",
errTypeExists: "exists",
errTypeInvalid: "invalid",
errTypeUnAuthed: "unauthed",
errTypeNotFound: "not found",
errTypeInternal: "internal",
}
var (
errIDRequired = InvalidErr("id is required")
)
// Err provides a lightly structured error that we can attach behavior. Additionally,
// the use of options makes it possible for us to enrich our logging infra without
// blowing up the message cardinality.
type Err struct {
Type int
Msg string
Fields []any
}
// Error returns the error message.
func (e Err) Error() string {
return e.Msg
}
// ExistsErr creates an exists error.
func ExistsErr(msg string, fields ...any) error {
return Err{
Type: errTypeExists,
Msg: msg,
Fields: fields,
}
}
func InvalidErr(msg string, fields ...any) error {
return Err{
Type: errTypeInvalid,
Msg: msg,
Fields: fields,
}
}
func InternalErr(msg string, fields ...any) error {
return Err{
Type: errTypeInternal,
Msg: msg,
Fields: fields,
}
}
// NotFoundErr creates a not found error.
func NotFoundErr(msg string, fields ...any) error {
return Err{
Type: errTypeNotFound,
Msg: msg,
Fields: fields,
}
}
func errFields(err error) []any {
var aErr Err
errors.As(err, &aErr)
return append(aErr.Fields, "err_type", errTypeStrs[aErr.Type])
}
func IsExistsErr(err error) bool {
return isErrType(err, errTypeExists)
}
func IsInvalidErr(err error) bool {
return isErrType(err, errTypeInvalid)
}
func IsNotFoundErr(err error) bool {
return isErrType(err, errTypeNotFound)
}
func isErrType(err error, want int) bool {
var aErr Err
return errors.As(err, &aErr) && aErr.Type == want
}