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