从 REST-ful 服务中为错误选择 HTTP 状态代码 [英] Picking HTTP status codes for errors from REST-ful services
问题描述
当客户端调用我的 REST-ful 服务时,它需要知道返回的响应是来自我"还是来自包含 Web 服务器的诊断,表明发生了可怕的事情.
When a client invokes my REST-ful service, it needs to know if the response came back was 'from me' or rather a diagnosis from the containing web server that something awful happened.
一种理论是,如果我的代码被调用,它应该总是返回一个 HTTP OK(=200),并且我必须返回的任何错误应该只在我返回的数据中表示.毕竟,得到响应的是我的代码,而不是裸浏览器.
One theory is that, if my code is called, it should always return an HTTP OK(=200), and any errors I've got to return should be just represented in the data I return. After all, it's my code that gets the response, not the naked browser.
不言而喻,如果我使用 REST 生成由浏览器直接读取的 HTML,如果出现错误,我绝对必须返回错误代码.在我关心的情况下,总是由 Javascript 或 Java 来解释响应的内脏.
Somewhat self-evidently, if I'm using REST to generate HTML read directly by a browser, I absolutely must return an error code if there's an error. In the case I care about, it's always Javascript or Java that is interpreting the entrails of the response.
另一种可能性是,有一些 HTTP 状态代码系列,我可以非常自信地返回它们/它们永远不会由周围容器中的问题生成.是这样吗?
Another possibility is that there is some family of HTTP status codes that I could return with a high confidence that it/they would never be generated by a problem in the surrounding container. Is this the case?
推荐答案
我使用以下内容:
获取
- 200 正常
- 400 Bad Request(当输入条件不正确时)
发布
- 202 Accepted(通过授权方式返回)
401 Unauthorized(也被授权返回)
- 202 Accepted (returned by authorization method)
401 Unauthorized (also returned by authorization)
201 Created(创建新资源时;我也设置了位置标题)
201 Created (when creating a new resource; I also set the location header)
PUT
与 POST 相同
- 201 好的
- 400 错误请求
删除
- 200 正常
- 404 未找到(与 GET 相同)
这篇关于从 REST-ful 服务中为错误选择 HTTP 状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!