/
err_trans.go
46 lines (39 loc) · 1.18 KB
/
err_trans.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
// Package middleware provide implementations of custom middleware for the echo framework.
package middleware
import (
"github.com/go-playground/universal-translator"
"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
"gopkg.in/go-playground/validator.v9"
"github.com/gozix/echo/errors"
)
// ErrTransConfig defines the config for ErrTransWithConfig middleware.
type ErrTransConfig struct {
Skipper middleware.Skipper
Translator *ut.UniversalTranslator
}
// ErrTransWithConfig returns echo.MiddlewareFunc.
func ErrTransWithConfig(conf ErrTransConfig) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
if conf.Skipper != nil && conf.Skipper(c) {
return next(c)
}
if err = next(c); err == nil {
return nil
}
if httpErr, ok := err.(*errors.HTTPError); ok {
if e, ok := httpErr.Cause.(validator.ValidationErrors); ok {
var trans = make(validator.ValidationErrorsTranslations)
for i := range e {
var fe = e[i]
trans[fe.Field()] = fe.Translate(conf.Translator.GetFallback())
}
httpErr.Description = trans
return httpErr
}
}
return err
}
}
}