将信息添加到Golang Gin HTTP错误响应中

huangapple go评论79阅读模式
英文:

Adding information to Golang Gin HTTP error responses

问题

我正在尝试在遇到HTTP 500内部错误时返回自定义错误响应。当发生数据库写入错误时,如果我使用c.JSON(http.StatusInternalServerError, CustomError{}),Gin会忽略我的CustomError结构体,并替换为默认的"500服务器错误"消息。

我如何在默认响应中添加信息或返回自定义响应,同时仍然使用HTTP 500内部服务器错误代码?

这是我想要实现的目标。通知用户在Mongo数据库中存在重复条目。Gin会忽略我的DBErrorResponse结构体,只返回默认的500错误JSON响应。

_, err := handler.collection.InsertOne(handler.ctx, data)
if err != nil {
    if mongo.IsDuplicateKeyError(err) {
        dbErr := err.(mongo.WriteException)
        c.JSON(
            http.StatusInternalServerError,
            models.DBErrorResponse{
                Type: "Write Exception",
                Code: dbErr.WriteErrors[0].Code,
                Err:  "similar record exists",
            })
        return
    }
}
英文:

I am trying to return a custom error response when an HTTP 500 Internal Error is encountered. If I use c.JSON(http.StatusInternalServerError, CustomError{}) when a database write error occurs, Gin ignores my CustomError struct and substitutes a default "500 server Error" message.

How can I add information to the default response or return a custom response while still using the HTTP 500 Internal Server error code?

This is what I am trying to accomplish. Notifying users of a duplicate entry in the Mongo database. Gin ignores my DBErrorResponse struct and just returns the default 500 error json response.

_, err := handler.collection.InsertOne(handler.ctx, data)
   if err != nil {
       if mongo.IsDuplicateKeyError(err) {
          dbErr := err.(mongo.WriteException)
           c.JSON(
               http.StatusInternalServerError,
               models.DBErrorResponse{
                   Type: "Write Exception",
                   Code: dbErr.WriteErrors[0].Code,
                   Err:  "similar record exists",
               })

           return
      }

答案1

得分: 2

如果错误是由用户提供重复的键引起的,那么这不是一个内部服务器错误。如果客户端提供了重复的值,你可能希望使用类似于BadRequest(400)的方法,这更适合处理重复值。因此,你应该能够返回一个带有状态码400的自定义错误消息。

此外,据我所知,InternalServerError(500)并不是设计用来向客户端提供“服务器端”问题反馈的,因为这不是公开信息。虽然我不能确定是否是这样,如果是的话,原因是什么。

更新:正如Gavin提到的,httpCode 409是更好的选择,这是文档中的说明:

HTTP 409错误状态:HTTP 409状态码(冲突)表示由于请求中的冲突,无法处理该请求,例如请求的资源不处于预期状态,或者处理该请求的结果将在资源内部创建冲突。

英文:

If the error is caused by a user providing a duplicate key, it's not an internal server error. You might want to use something like BadRequest(400), which suits duplicate value far more, if provided by the client. Thus, you should be able to return a custom error message with StatusCode 400.

Additionally, as far as I know, InternalServerError(500) is not designed to provide a 'server-side' problem feedback to the client, since, well, it's not public information. Although I'm not certainly sure if that's so and if is, why.

UPD: As Gavin mentioned, httpCode 409 is far better choice, here is the doc:
>HTTP 409 error status: The HTTP 409 status code (Conflict) indicates that the request could not be processed because of conflict in the request, such as the requested resource is not in the expected state, or the result of processing the request would create a conflict within the resource.

huangapple
  • 本文由 发表于 2023年1月20日 02:57:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75177073.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定