我有一个用golang 4 * 3 * 2 * 1
编写的应用程序。我想编写一个中间件来自定义所有错误消息,特别是在gin framework
的情况下。
这是中间件:
BindJSON
该功能非常简单,它可以获取所有func Errors() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
// Only run if there are some errors to handle
if len(c.Errors) > 0 {
for _, e := range c.Errors {
// Find out what type of error it is
switch e.Type {
case gin.ErrorTypePublic:
// Only output public errors if nothing has been written yet
if !c.Writer.Written() {
c.JSON(c.Writer.Status(), gin.H{"Error": e.Error()})
}
case gin.ErrorTypeBind:
errs := e.Err.(validator.ValidationErrors)
list := make(map[int]string)
fmt.Println(errs)
for field, err := range errs {
list[field] = validationErrorToText(err)
}
// Make sure we maintain the preset response status
status := http.StatusBadRequest
if c.Writer.Status() != http.StatusOK {
status = c.Writer.Status()
}
c.JSON(status, gin.H{"Errors": list})
default:
c.JSON(http.StatusBadRequest, gin.H{"Errors": c.Errors.JSON()})
}
}
// If there was no public or bind error, display default 500 message
if !c.Writer.Written() {
c.JSON(http.StatusInternalServerError, gin.H{"Error": errorInternalError.Error()})
}
}
}
}
错误,并根据错误类型执行某些操作!问题是在gin
的情况下,我尝试将错误映射到验证错误:gin.ErrorTypeBind
。
我遇到了这个错误
e.Err.(validator.ValidationErrors)
这是导入软件包的列表:
interface conversion: error is validator.ValidationErrors, not validator.ValidationErrors (types from different packages)
答案 0 :(得分:1)
看着source code of gin,我看到了:
import (
"gopkg.in/go-playground/validator.v8"
)
但是您正在使用"gopkg.in/go-playground/validator.v9"