Skip to content

Commit

Permalink
slightly improved validation error messages with extra debug info
Browse files Browse the repository at this point in the history
  • Loading branch information
Shai Nagar committed May 15, 2021
1 parent 4064e9f commit 567727a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ go 1.15

require (
github.com/fatih/color v1.10.0
github.com/go-playground/locales v0.13.0
github.com/go-playground/universal-translator v0.17.0
github.com/go-playground/validator/v10 v10.6.1
github.com/leodido/go-urn v1.2.1 // indirect
github.com/montanaflynn/stats v0.6.6
Expand Down
34 changes: 33 additions & 1 deletion internal/spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,18 @@ package internal

import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
log "github.com/sirupsen/logrus"

"github.com/go-playground/locales/en"
ut "github.com/go-playground/universal-translator"

"github.com/go-playground/validator/v10"
en_translations "github.com/go-playground/validator/v10/translations/en"

"gopkg.in/yaml.v2"
)

Expand Down Expand Up @@ -73,5 +80,30 @@ func load(path string, unmarshal func([]byte, interface{}) error) (spec *Benchma

func validate(spec *BenchmarkSpec) (err error) {
v := validator.New()
return v.Struct(spec)
english := en.New()
uni := ut.New(english, english)
trans, _ := uni.GetTranslator("en")
_ = en_translations.RegisterDefaultTranslations(v, trans)

if err = v.Struct(spec); err != nil {
var errstrings []string
errstrings = append(errstrings, "Invalid configuration:")
errstrings = append(errstrings, translateError(err, trans)...)
err = fmt.Errorf(strings.Join(errstrings, "\n\t- "))
}

return err
}

func translateError(err error, trans ut.Translator) (errs []string) {
if err == nil {
return nil
}
validatorErrs := err.(validator.ValidationErrors)
for _, e := range validatorErrs {
translatedErr := fmt.Errorf(e.Translate(trans))
log.Debug(e)
errs = append(errs, translatedErr.Error())
}
return errs
}

0 comments on commit 567727a

Please sign in to comment.