-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy patherrors.go
96 lines (80 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
91
92
93
94
95
96
package validating
import (
"fmt"
"strings"
)
const (
ErrUnsupported = "UNSUPPORTED" // errors reported to developers. (panic is more appropriate?)
ErrInvalid = "INVALID" // errors reported to users.
)
type Error interface {
error
Field() string
Kind() string
Message() string
}
type Errors []Error
func NewErrors(field, kind, message string) Errors {
return []Error{NewError(field, kind, message)}
}
func NewUnsupportedErrors(validatorName string, field *Field, want ...any) Errors {
var wantTypes []string
for _, w := range want {
t := fmt.Sprintf("%T", w)
if t == "[]uint8" {
t = "[]byte" // []uint8 => []byte
}
wantTypes = append(wantTypes, t)
}
expected := strings.Join(wantTypes, " or ")
return NewErrors(field.Name, ErrUnsupported, fmt.Sprintf("%s expected %s but got %T", validatorName, expected, field.Value))
}
func NewInvalidErrors(field *Field, msg string) Errors {
return NewErrors(field.Name, ErrInvalid, msg)
}
func (e *Errors) Append(errs ...Error) {
*e = append(*e, errs...)
}
func (e Errors) Error() string {
strs := make([]string, len(e))
for i, err := range e {
strs[i] = err.Error()
}
return strings.Join(strs, ", ")
}
// Map converts the given errors to a map[string]Error, where the keys
// of the map are the field names.
func (e Errors) Map() map[string]Error {
if len(e) == 0 {
return nil
}
m := make(map[string]Error, len(e))
for _, err := range e {
m[err.Field()] = err
}
return m
}
type errorImpl struct {
field string
kind string
message string
}
func NewError(field, kind, message string) Error {
return errorImpl{field, kind, message}
}
func (e errorImpl) Field() string {
return e.field
}
func (e errorImpl) Kind() string {
return e.kind
}
func (e errorImpl) Message() string {
return e.message
}
func (e errorImpl) Error() string {
s := fmt.Sprintf("%s(%s)", e.kind, e.message)
if e.field == "" {
return s
}
return fmt.Sprintf("%s: %s", e.field, s)
}