从 REST 服务中挑选错误的 HTTP 状态代码
当客户端调用我的 REST 式服务时,它需要知道返回的响应是“来自我”,还是来自包含 Web 服务器的诊断,表明发生了可怕的事情。
一种理论是,如果我的代码被调用,它应该始终返回 HTTP OK(=200),并且我必须返回的任何错误都应该只在我返回的数据中表示。毕竟,是我的代码获得响应,而不是裸露的浏览器。
不言而喻的是,如果我使用 REST 生成由浏览器直接读取的 HTML,那么如果出现错误,我绝对必须返回错误代码。在我关心的情况下,总是由 Javascript 或 Java 来解释响应的内容。
另一种可能性是,有一些 HTTP 状态代码系列,我可以高度确信它/它们永远不会由周围容器中的问题生成。是这样吗?
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.
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.
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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我使用以下内容:
GET
POST
401 未经授权(也由授权方法返回)授权)
201 已创建(创建新资源时;我还设置了位置标头)
PUT
与 POST 相同
DELETE
I use the following:
GET
POST
401 Unauthorized (also returned by authorization)
201 Created (when creating a new resource; I also set the location header)
PUT
Same as POST
DELETE
我不知道如何避免某些容器返回诸如
404.4xx 代码之类的代码,其目的是处理客户端错误以及可能的一些详细描述问题的实体(因此意味着您提到的两种方法的组合)。由于 REST 依赖于 HTTP 以及相应的状态语义和方法,因此在任何可能的情况下始终返回 200 在我看来都违反了这一原则。
例如,如果您有一个诸如
http://foo.com/bar/123
的请求,它代表带有id=123
的bar
资源当你返回 200 并包含一些内容时,客户端没有机会弄清楚这是预期的响应还是发生了某种错误。因此,应该尝试将错误条件映射到状态代码,如 REST 中所述:例如,将应用程序错误映射到 HTTP 状态代码。I would not know how to avoid that some container returns codes like 404.
4xx codes are meant to handle client errors along with possibly some entity that describes the problem in detail (and thus would mean a combination of both of your mentioned approaches). Since REST relies on HTTP and the according semantics of status as well as methods, always returning 200 in any possible case is a violation of this principle in my opinion.
If you for instance have a request such as
http://foo.com/bar/123
which represents abar
ressource withid=123
and you return 200 with some content, the client has no chance to figure out if this was the intended response or some sort of error that occured. Therefore one should try to map error conditions to status codes as discussed in REST: Mapping application errors to HTTP Status codes for example.