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

enter image description here

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?



Solution 1:[1]

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
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 blackgreen