/
errors.go
83 lines (68 loc) · 1.5 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
package validating
import (
"fmt"
"strings"
)
const (
ErrUnsupported = "UNSUPPORTED"
ErrInvalid = "INVALID"
)
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(field *Field, validatorName string) Errors {
return NewErrors(field.Name, ErrUnsupported, fmt.Sprintf("cannot use validator `%s` on type %T", validatorName, field.Value))
}
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)
}