-
Notifications
You must be signed in to change notification settings - Fork 617
/
errors.go
58 lines (50 loc) · 1.16 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
package validate
import (
"encoding/json"
"errors"
)
// FieldError is used to indicate an error with a specific request field.
type FieldError struct {
Field string `json:"field"`
Err string `json:"error"`
}
// FieldErrors represents a collection of field errors.
type FieldErrors []FieldError
// NewFieldsError creates an fields error.
func NewFieldsError(field string, err error) error {
return FieldErrors{
{
Field: field,
Err: err.Error(),
},
}
}
// Error implements the error interface.
func (fe FieldErrors) Error() string {
d, err := json.Marshal(fe)
if err != nil {
return err.Error()
}
return string(d)
}
// Fields returns the fields that failed validation
func (fe FieldErrors) Fields() map[string]string {
m := make(map[string]string, len(fe))
for _, fld := range fe {
m[fld.Field] = fld.Err
}
return m
}
// IsFieldErrors checks if an error of type FieldErrors exists.
func IsFieldErrors(err error) bool {
var fe FieldErrors
return errors.As(err, &fe)
}
// GetFieldErrors returns a copy of the FieldErrors pointer.
func GetFieldErrors(err error) FieldErrors {
var fe FieldErrors
if !errors.As(err, &fe) {
return nil
}
return fe
}