Description

Unlike the ShouldBindJSON function, ShouldBindQuery returns a strconv error instead of Validation or UnMarshal error, which results in loss of error details, such as name of the attribute that is causing the issue.

How to reproduce

package main

import (
    "encoding/json"
    "errors"
    "log"
    "strconv"

    "github.com/gin-gonic/gin"
)

type Person struct {
    Name string `form:"name"`
    Age  int    `form:"age"`
}

func main() {
    route := gin.Default()
    route.Any("/testing", startPage)
    route.Run(":8085")
}

func startPage(c *gin.Context) {
    var person Person
    if err := c.ShouldBindQuery(&person); err == nil {
        log.Printf("Name: %v", person.Name)
        log.Printf("Age: %v", person.Age)
    } else {
        var jsonUnMarshalTypeErr *json.UnmarshalTypeError
        var strConvErr *strconv.NumError
        if errors.As(err, &jsonUnMarshalTypeErr) {
            log.Printf("JSON UnMarshalType error encountered: %v", jsonUnMarshalTypeErr)
        } else if errors.As(err, &strConvErr) {
            log.Printf("String Conversion Error: %v", strConvErr)
        } else {
            log.Printf("Error binding: %v", err.Error())
        }
    }
    c.String(200, "Done")
}

Expectation

$ curl "localhost:8085/testing? Name=Tester&age=d"

The error returned should include the attribute name as in the case of ShouldBindJSON. "json: cannot unmarshal string into Go struct field Person.age of type int"

Actual result

The following error loses the name of the attribute causing the problem. "strconv.ParseInt: parsing "d": invalid syntax"

Environment

  • go version: 1.19
  • gin version (or commit ref): v1.8.2
  • Validator: v10.11.2
  • operating system: Mac OS

Comment From: rnotorni

Since it is a form, I feel that Unmarshal of json cannot be executed easily (because all values ​​are strings)

I think it is necessary to wrap the error around here when displaying the field name.