When there is a field type error in the JSON sent from the frontend, an error occurs stating that the JSON parsing has failed. I have a custom validator, but it only validates the field content when the JSON parsing is successful. In the case of JSON parsing failure, I cannot obtain errors of type validator.ValidationErrors; I can only get json.UnmarshalTypeError. Is there any way to customize the content of this JSON parsing error?
"json: cannot unmarshal number into Go struct field argsLogin.Username of type string"
my controller code:
func (l *Login) Login(c *gin.Context) {
args := argsLogin{}
if err := c.ShouldBind(&args); err != nil {
bean.Response.ResultFail(c, 10001, common.GetVerErr(err))
return
}
login, err := manage.LoginLogic.Login(args.Username, args.Password, common.GetDeviceType(c), constant.SystemTerminalAdmin)
if err != nil {
bean.Response.ResultFail(c, 10002, err.Error())
return
}
bean.Response.ResultSuc(c, "登录成功", &login)
}
my validator:
func GetVerErr(err error) string {
er, ok := err.(validator.ValidationErrors)
if ok {
field := er[0].Field()
if field == er[0].StructField() {
field = strings.ToLower(field[0:1]) + field[1:]
}
switch er[0].Tag() {
case "required":
return field + "不能为空"
case "min":
if er[0].Type().String() == "string" {
return field + "不能小于" + er[0].Param() + "位"
}
return field + "不能小于" + er[0].Param()
case "gte":
if er[0].Type().String() == "string" {
return field + "不能小于" + er[0].Param() + "位"
}
return field + "不能小于" + er[0].Param()
}
return field + "错误"
} else {
return "参数格式错误"
}
}
I can replace the entire string of the error message, but I want to take it a step further and indicate which field failed to parse. How can I obtain the field that caused the parsing failure?
When there is a field type error in the JSON sent from the frontend, an error occurs stating that the JSON parsing has failed. I have a custom validator, but it only validates the field content when the JSON parsing is successful. In the case of JSON parsing failure, I cannot obtain errors of type validator.ValidationErrors; I can only get json.UnmarshalTypeError. Is there any way to customize the content of this JSON parsing error?
my controller code:
my validator:
I can replace the entire string of the error message, but I want to take it a step further and indicate which field failed to parse. How can I obtain the field that caused the parsing failure?