接口转换:错误是*errors.errorString,而不是validator.ValidationErrors。

huangapple go评论87阅读模式
英文:

interface conversion: error is *errors.errorString, not validator.ValidationErrors

问题

type BookInput struct {
    Title string `json:"title" binding:"required"`
    Price json.Number `json:"price" binding:"required,number"`
}

func PostBookHandler(ctx *gin.Context) {
    var bookInput BookInput

    err := ctx.ShouldBindJSON(&bookInput)

    if err != nil {
        errorMessages := []string{}

        for _, e := range err.(validator.ValidationErrors) {
            errorMessage := fmt.Sprintf("字段 %s 上的错误,条件:%s", e.Field(), e.ActualTag())
            errorMessages = append(errorMessages, errorMessage)
        }

        ctx.JSON(http.StatusBadRequest, gin.H{
            "errors": errorMessages,
        })
        return
    }

    ctx.JSON(http.StatusOK, gin.H{
        "title": bookInput.Title,
        "price": bookInput.Price,
    })
}

我尝试验证价格输入,但得到的结果出乎意料。我写的代码如上所示,有人可以帮我吗?

英文:

接口转换:错误是*errors.errorString,而不是validator.ValidationErrors。

type BookInput struct {
  Title string `json:"title" binding:"required"`
  Price json.Number `json:"price" binding:"required,number"`
}

func PostBookHandler(ctx *gin.Context) {
  var bookInput book.BookInput

  err := ctx.ShouldBindJSON(&bookInput)

  if err != nil {
	errorMessages := []string{}

	for _, e := range err.(validator.ValidationErrors) {
		errorMessage := fmt.Sprintf("Error on filed %s, condition: %s", e.Field(), e.ActualTag())
		errorMessages = append(errorMessages, errorMessage)
	}

	ctx.JSON(http.StatusBadRequest, gin.H {
		"errors": errorMessages, 
	})
	return
  }

  ctx.JSON(http.StatusOK, gin.H {
	"title": bookInput.Title,
	"price": bookInput.Price,
  })
} 

I tried to validate the price input, but the results I got were unexpected. The code I wrote is like the one above, can someone help me?

答案1

得分: 1

在这种情况下返回的错误可能不是validator.ValidationErrors,可能是其他东西。例如,如果请求体无效的 JSON,那么根本不会执行验证步骤。

在你的代码中,你执行了一个未经检查的断言 range err.(validator.ValidationErrors),这可能会导致 panic。

以下是如何有条件地处理错误的示例代码:

err := ctx.ShouldBindJSON(&bookInput)
if err != nil {
    var ve validator.ValidationErrors
    if errors.As(err, &ve) {
       // 处理验证器错误
    }
    // 处理非验证器错误
    return
}
英文:

The error returned in this case might not be a validator.ValidationErrors, it could be something else. For example if the body is invalid JSON, then the validation step isn’t reached at all.

In your code you are performing an unchecked assertion range err.(validator.ValidationErrors) which could panic.

This is how you could conditionally handle the error:

err := ctx.ShouldBindJSON(&bookInput)
if err != nil {
    var ve validator.ValidationErrors
    if errors.As(err, &ve) {
       // handle validator error
    }
    // handle non-validator error
    return
}

答案2

得分: 1

也许这可以帮助:

type BookInput struct {
    Title string `json:"title" binding:"required"`
    
    Price interface{} `json:"price" binding:"required,number"`
}

func postBooksHandler(c *gin.Context) {
    var bookInput BookInput

    err := c.ShouldBindJSON(&bookInput)
    if err != nil {

        errorMessages := []string{}
        for _, e := range err.(validator.ValidationErrors) {
            errorMessage := fmt.Sprintf("字段 %s 上的错误,条件:%s", e.Field(), e.ActualTag())
            errorMessages = append(errorMessages, errorMessage)

        }
        c.JSON(http.StatusBadRequest, gin.H{
            "error": errorMessages,
        })
        return
    }
    c.JSON(http.StatusOK, gin.H{
        "title": bookInput.Title,
        "price": bookInput.Price,
    })

}

希望对你有帮助!

英文:

Maybe it can help:

type BookInput struct {
	Title string `json:"title" binding:"required"`
	
	Price interface{} `json:"price" binding:"required,number"`
}

func postBooksHandler(c *gin.Context) {
	var bookInput BookInput

	err := c.ShouldBindJSON(&bookInput)
	if err != nil {

		errorMessages := []string{}
		for _, e := range err.(validator.ValidationErrors) {
			errorMessage := fmt.Sprintf("Error on field %s, conditon: %s", e.Field(), e.ActualTag())
			errorMessages = append(errorMessages, errorMessage)

		}
		c.JSON(http.StatusBadRequest, gin.H{
			"error": errorMessages,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"title": bookInput.Title,
		"price": bookInput.Price,
	})

}

答案3

得分: 0

需要在错误上创建两个条件,因为validator.ValidationErrors并不能覆盖所有情况。

这是我的代码:

if err != nil {
    var ve validator.ValidationErrors
    if errors.As(err, &ve) {
        for _, e := range err.(validator.ValidationErrors) {
            c.JSON(http.StatusBadRequest, gin.H{
                "error":   true,
                "message": "" + e.Field() + "为空",
            })
            return
        }
    }
    c.JSON(http.StatusBadRequest, gin.H{
        "error":   true,
        "message": err.Error(),
    })
}
英文:

Need to create two conditions on error, because validator.ValidationErrors doesn't cover everything.

This my code:

if err != nil {
	var ve validator.ValidationErrors
	if errors.As(err, &ve) {
		for _, e := range err.(validator.ValidationErrors) {
			c.JSON(http.StatusBadRequest, gin.H{
				"error":   true,
				"message": "" + e.Field() + " kosong",
			})
			return
		}
	}
	c.JSON(http.StatusBadRequest, gin.H{
		"error":   true,
		"message": err.Error(),
	})
}

huangapple
  • 本文由 发表于 2022年3月14日 02:51:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/71459830.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定