У меня есть приложение, написанное с помощью golang 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)
вот список импортируемых пакетов:
import (
"errors"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
"gopkg.in/go-playground/validator.v9"
)