I have an error when validating the number in gin, for the string data type there are no errors and they are detected, but when I fill in the price field of type int with a string, it gets an error of 500, I expect the error to be 400, what is the solution?
package web
type BookRequest struct{
Title string `json:"title" binding:"required"`
Description string `json:"description" binding:"required"`
Price int `json:"price" binding:"required,numeric,gte=0"`
Rating int `json:"rating" binding:"required,numeric"`
}
func (controller *BookControllerImpl) Create(ctx *gin.Context) {
var bookRequest web.BookRequest
err := ctx.ShouldBindJSON(&bookRequest)
if err != nil {
var error_request []string
for _, e := range err.(validator.ValidationErrors) {
errorMessage := fmt.Sprintf("Error field %s, Condition %s", e.Field(), e.ActualTag())
error_request = append(error_request, errorMessage)
}
ctx.JSON(http.StatusBadRequest, web.WebResponse{
Code: http.StatusBadRequest,
Status: "BAD REQUEST",
Data: error_request,
})
return
}
book, err := controller.BookService.Create(bookRequest)
if err != nil {
ctx.JSON(http.StatusBadRequest, web.WebResponse{
Code: http.StatusBadRequest,
Status: "BAD REQUEST",
Data: err,
})
}
ctx.JSON(http.StatusOK, web.WebResponse{
Code: 200,
Status: "Ok",
Data: book,
})
}