-
Notifications
You must be signed in to change notification settings - Fork 69
/
errors.go
64 lines (55 loc) · 2.14 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
// Package edgegriderr is used for parsing validation errors to make them more readable.
// It formats error(s) in a way, that the return value is one formatted error type, consisting of all the errors that occurred
// in human-readable form. It is important to provide all the validation errors to the function.
// Usage example:
//
// error := edgegriderr.ParseValidationErrors(validation.Errors{
// "Validation1": validation.Validate(...),
// "Validation2": validation.Validate(...),
// })
package edgegriderr
import (
"fmt"
"sort"
"strconv"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
)
// ParseValidationErrors parses validation errors into easily readable form
// The output error is formatted with indentations and struct field indexing for collections
func ParseValidationErrors(e validation.Errors) error {
if e.Filter() == nil {
return nil
}
parser := validationErrorsParser()
return fmt.Errorf("%s", strings.TrimSuffix(parser(e, "", 0), "\n"))
}
// validationErrorsParser returns a function that parses validation errors
// Returned function takes validation.Errors, field to be indexed (empty at the beginning) and index size at start as parameters
func validationErrorsParser() func(validation.Errors, string, int) string {
var parser func(validation.Errors, string, int) string
parser = func(validationErrors validation.Errors, indexedFieldName string, indentSize int) string {
keys := make([]string, 0, len(validationErrors))
for k := range validationErrors {
keys = append(keys, k)
}
sort.Strings(keys)
var s strings.Builder
for _, key := range keys {
if validationErrors[key] == nil {
continue
}
errs, ok := validationErrors[key].(validation.Errors)
if !ok {
fmt.Fprintf(&s, "%s%s: %s\n", strings.Repeat("\t", indentSize), key, validationErrors[key].Error())
}
if _, err := strconv.Atoi(key); err != nil {
fmt.Fprintf(&s, "%s", parser(errs, key, indentSize))
continue
}
fmt.Fprintf(&s, "%s%s[%s]: {\n%s%s}\n", strings.Repeat("\t", indentSize), indexedFieldName, key, parser(errs, "", indentSize+1), strings.Repeat("\t", indentSize))
}
return s.String()
}
return parser
}