github.com/akamai/AkamaiOPEN-edgegrid-golang/v2@v2.17.0/pkg/edgegriderr/errors.go (about) 1 package edgegriderr 2 3 import ( 4 "fmt" 5 "sort" 6 "strconv" 7 "strings" 8 9 validation "github.com/go-ozzo/ozzo-validation/v4" 10 ) 11 12 // ParseValidationErrors parses validation errors into easily readable form 13 // The output error is formated with indentations and struct field indexing for collections 14 func ParseValidationErrors(e validation.Errors) error { 15 if e.Filter() == nil { 16 return nil 17 } 18 19 parser := validationErrorsParser() 20 return fmt.Errorf("%s", strings.TrimSuffix(parser(e, "", 0), "\n")) 21 } 22 23 // validationErrorsParser returns a function that parses validation errors 24 // Returned function takes validation.Errors, field to be indexed (empty at the beginning) and index size at start as parameters 25 func validationErrorsParser() func(validation.Errors, string, int) string { 26 var parser func(validation.Errors, string, int) string 27 parser = func(validationErrors validation.Errors, indexedFieldName string, indentSize int) string { 28 keys := make([]string, 0, len(validationErrors)) 29 for k := range validationErrors { 30 keys = append(keys, k) 31 } 32 sort.Strings(keys) 33 34 var s strings.Builder 35 for _, key := range keys { 36 if validationErrors[key] == nil { 37 continue 38 } 39 errs, ok := validationErrors[key].(validation.Errors) 40 41 if !ok { 42 fmt.Fprintf(&s, "%s%s: %s\n", strings.Repeat("\t", indentSize), key, validationErrors[key].Error()) 43 } 44 if _, err := strconv.Atoi(key); err != nil { 45 fmt.Fprintf(&s, "%s", parser(errs, key, indentSize)) 46 continue 47 } 48 fmt.Fprintf(&s, "%s%s[%s]: {\n%s%s}\n", strings.Repeat("\t", indentSize), indexedFieldName, key, parser(errs, "", indentSize+1), strings.Repeat("\t", indentSize)) 49 } 50 51 return s.String() 52 } 53 54 return parser 55 }