我可以使用 HTTP 状态代码的自定义原因来区分 REST API 的错误吗
我想区分不同类型的“未找到”错误。例如,给出以下请求:
GET /author/Adams/works/HHGTTG
作者可能“找不到”,或者作品可能“找不到”,我想区分两者。
状态:404 - 找不到作者
状态:404 - 找不到工作
根据规范,可以更改原因短语。 http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html
6.1.1 状态代码和原因短语
...此处列出的原因短语只是建议 - 它们可以被本地等效项替换,而不影响协议...
对于同一状态代码使用两个唯一的短语是否也可以接受?
而且,这是一种合理的方法还是有更好的约定来指示更细粒度的错误?
最终,我希望有一个客户端库可以抛出 AuthorNotFound 或 WorkNotFound 异常,而不是通用的 AuthorOrWorkNotFound 异常。
I want to differentiate between separate types of "Not Found" errors. For Example given the following request:
GET /author/Adams/works/HHGTTG
Either the author could be 'not found' or the work could be'not found' and I want to differentiate between the two.
status: 404 - author not found
status: 404 - work not found
According to the spec the reason phrase can be changed.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec6.html
6.1.1 Status Code and Reason Phrase
...The reason phrases listed here are only recommendations -- they MAY be replaced by local equivalents without affecting the protocol...
Is it also acceptable to use two unique phrases for the same status code?
And, is this a sound approach or is there a better convention for indicating more granular errors?
Ultimately I want to have a client library that could throw either an AuthorNotFound or WorkNotFound exception instead of a generic AuthorOrWorkNotFound exception.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以让 HTTP 响应的正文包含一条消息,您可以使用任何附加信息来解析该消息。
状态代码(在响应中)上的 HTTP 状态消息可以是您想要的任何内容,并且不会影响任何客户端。 HTTP 客户端通常会忽略消息文本。
You could have the body of the HTTP response contain a message which you can parse with any additional information.
The HTTP status message on the status code (in the response) can be anything you want and it won't effect any clients. HTTP clients usually ignore the message text.
当使用“隐藏”未找到方法时,您可以使用带有响应正文的 404:
不过我不推荐上面提到的子代码,它们为统一的 HTTP 接口增加了很多复杂性和维护工作。以不同的方式构建 api 客户端库。让它先调用
/author/adams/work/11
。如果返回 404,则接下来调用/author/adams/
来查明是否是缺少作者导致了 404。然后您可以抛出相应的 NotFound 异常。另一种选择是以不同的方式设计最终 api 客户端应用程序。它首先应该调用
/author/adams
,然后如果不是 404,将继续/author/adams/work
。因此,应用程序本身自然会沿着这条路走下去。但这当然只有在前端内的页面流适应此调用序列时才有效。When using your "shadowed" not found approach, you could do use 404 with response body:
Still I do NOT recommend above mentioned sub-codes, they add a lot of complexity and maintenance effort for uniform HTTP interface. Structure your api-client library differently. Let it call
/author/adams/work/11
first. If it returns 404 then call/author/adams/
next to find out whether it was the missing author which caused the 404. You then can throw respective NotFound exceptions.Another alternative is to design the end api-client application differently. It first should call
/author/adams
then if not 404 would proceed/author/adams/work
. So naturally the application itself is descending the path. But this of course only works if your page flow inside frontend adapts to this call sequence.