Skip to content

Commit

Permalink
better errors on validation
Browse files Browse the repository at this point in the history
  • Loading branch information
gmgigi96 committed Jul 4, 2023
1 parent b312d97 commit e917a9c
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion pkg/utils/cfg/cfg.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,12 @@
package cfg

import (
"errors"

"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"
"github.com/mitchellh/mapstructure"
)

Expand All @@ -31,6 +36,10 @@ type Setter interface {
}

var validate = validator.New()
var english = en.New()
var uni = ut.New(english, english)
var trans, _ = uni.GetTranslator("en")
var _ = en_translations.RegisterDefaultTranslations(validate, trans)

// Decode decodes the given raw input interface to the target pointer c.
// It applies the default configuration if the target struct
Expand All @@ -53,5 +62,17 @@ func Decode(input map[string]any, c any) error {
return err
}

return validate.Struct(c)
return translateError(validate.Struct(c), trans)
}

func translateError(err error, trans ut.Translator) error {
if err == nil {
return nil
}
errs := err.(validator.ValidationErrors)
translated := make([]error, 0, len(errs))
for _, err := range errs {
translated = append(translated, errors.New(err.Translate(trans)))
}
return errors.Join(translated...)
}

0 comments on commit e917a9c

Please sign in to comment.