为什么golang go-gin错误总是返回空对象

hrirmatl  于 2023-01-18  发布在  Go
关注(0)|答案(2)|浏览(169)

我正在尝试解析gin golang中的错误验证,但生成了空对象“{}”
这是我的第一次尝试:

resp, err := userService.UserRegistrationService(c)

if err != nil {
    c.JSON(http.StatusBadRequest, gin.H{"error": err})
    return
}

返回:

{
    "error": [
        {},
        {}
    ]
}

下面是我的第二次尝试:

resp, err := userService.UserRegistrationService(c)

if err != nil {
    dada := fmt.Errorf("%v", err)
    c.JSON(http.StatusBadRequest, dada)
    return
}

返回

{}

如果我调试了err参数,请看一下:

resp, err := userService.UserRegistrationService(c)
    fmt.Println(err)
    if err != nil {
        dada := fmt.Errorf("%v", err)
        fmt.Println(dada)
        c.JSON(http.StatusBadRequest, dada)
        return
    }

它的回报:

2020/11/10 12:41:46 stdout: Key: 'User.Email' Error:Field validation for 'Email' failed on the 'required' tag
2020/11/10 12:41:46 stdout: Key: 'User.Password' Error:Field validation for 'Password' failed on the 'required' tag

你们能帮我一下吗,试着到处找还是没有运气,我想这样回报:

{
    "MyRequestStruct.PropertyOne": {
        "FieldNamespace": "MyRequestStruct.PropertyOne",
        "NameNamespace": "PropertyOne",
        "Field": "PropertyOne",
        "Name": "PropertyOne",
        "Tag": "required",
        "ActualTag": "required",
        "Kind": 24,
        "Type": {},
        "Param": "",
        "Value": ""
    },
    "MyRequestStruct.PropertyTwo": {
        "FieldNamespace": "MyRequestStruct.PropertyTwo",
        "NameNamespace": "PropertyTwo",
        "Field": "PropertyTwo",
        "Name": "PropertyTwo",
        "Tag": "required",
        "ActualTag": "required",
        "Kind": 24,
        "Type": {},
        "Param": "",
        "Value": ""
    }
}
mznpcxlj

mznpcxlj1#

发布为json响应时,应尝试err.Error()而不是err
试试这个:

resp, err := userService.UserRegistrationService(c)

if err != nil {
    c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    return
}
wswtfjt7

wswtfjt72#

如何使用它而不返回空值?

resp, err := userService.UserRegistrationService(c)

if err != nil {
  c.JSON(http.StatusBadRequest, gin.H{
    "error": err.Error()
  })

  return

}

相关问题