且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我应该在我的 REST API 中什么时候使用信封?如果我在一个地方使用它,我应该一直使用它吗?

更新时间:2021-12-02 06:02:42

HTTP 你的信封.通过返回 4** 错误代码,您做的是正确的事情.

HTTP is your envelope. You're doing the right thing by returning a 4** error code.

话虽如此,在响应中使用描述性正文并没有错——事实上HTTP RFC,大多数 HTTP 错误代码都提倡您确实返回错误发生原因的描述.例如参见 403:

Having said that, there is nothing wrong with having a descriptive body on a response – in fact in the HTTP RFC, most of the HTTP Error codes advocate that you do return a description of why the error occurred. See 403 for example:

如果请求方法不是 HEAD 并且服务器希望公开请求未完成的原因,它应该在实体中描述拒绝的原因.

If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity.

因此,您可以继续使用响应正文来更详细地描述错误.如果您不确定要使用的特定 HTTP 错误响应(例如多个错误),并且您知道用户不应该像刚刚那样重复请求,我通常会回退到使用 400.

So you're okay to continue to use the body of a response for a more detailed description of the error(s). If you're unsure of the specific HTTP error response to use (e.g. multiple errors), and you know that the user should not repeat the request as they just did it, I usually fall back to using 400.