简体   繁体   English

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

[英]Why golang go-gin error always returning empty object

im trying to parse error validation in gin golang, but produce an empty object "{}"我试图在 gin golang 中解析错误验证,但生成一个空的 object“{}”

Here is my 1st attempt:这是我的第一次尝试:

resp, err := userService.UserRegistrationService(c)

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

returning:返回:

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

Here is my 2nd attempt:这是我的第二次尝试:

resp, err := userService.UserRegistrationService(c)

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

returning返回

{}

Take a look if I debug the err parameter:看看我是否调试了 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
    }

Its 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

Can you guys help me, trying to search anywhere still no luck, I want return like this:你们能帮帮我吗,尝试在任何地方搜索仍然没有运气,我想这样返回:

{
    "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": ""
    }
}

You should try err.Error() instead of err while publishing as json response.在发布为json响应时,您应该尝试err.Error()而不是err

Try this :尝试这个 :

resp, err := userService.UserRegistrationService(c)

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

how to use it without an empty return?如何在没有空返回的情况下使用它?

resp, err := userService.UserRegistrationService(c)

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

  return

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM