-
Notifications
You must be signed in to change notification settings - Fork 0
/
field_error.go
88 lines (70 loc) · 1.57 KB
/
field_error.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
package buzz
import "fmt"
const (
invalidTypeMsg = "invalid type. expected: %s received: %T"
notNullableMsg = "%s is not nullable"
nonEmptyMsg = "%s can not be empty"
)
type FieldError struct {
Name string
Constraint string
Message string
}
func MakeFieldError(name, constraint, message string) FieldError {
return FieldError{
Name: name,
Constraint: constraint,
Message: message,
}
}
func (e FieldError) Error() string {
return e.Message
}
func notNullableFieldErr(name string) FieldError {
return MakeFieldError(name, "Nonnil", fmt.Sprintf(notNullableMsg, name))
}
func nonEmptyFieldErr(name string) FieldError {
return MakeFieldError(name, "Nonempty", fmt.Sprintf(nonEmptyMsg, name))
}
type FieldErrorAggregator struct {
Errors []FieldError
}
func NewFieldErrorAggregator() *FieldErrorAggregator {
return &FieldErrorAggregator{}
}
func (a *FieldErrorAggregator) Error() string {
if a.Empty() {
return ""
}
return a.Errors[0].Error()
}
func (a *FieldErrorAggregator) Handle(err error) error {
switch e := err.(type) {
case FieldError:
a.Add(e)
break
case *FieldErrorAggregator:
a.Merge(e)
break
default:
return err
}
return nil
}
func (a *FieldErrorAggregator) Add(err FieldError) {
a.Errors = append(a.Errors, err)
}
func (a *FieldErrorAggregator) Merge(aggr *FieldErrorAggregator) {
if !aggr.Empty() {
a.Errors = append(a.Errors, aggr.Errors...)
}
}
func (a *FieldErrorAggregator) Empty() bool {
return len(a.Errors) == 0
}
func (a *FieldErrorAggregator) OrNil() error {
if a.Empty() {
return nil
}
return a
}