当涉及到REST API的返回错误时,我正在寻找关于良好实践的指导。我正在开发一个新的API,所以我现在可以把它带到任何方向。目前我的内容类型是XML,但我计划将来支持JSON。

I am now adding some error cases, like for instance a client attempts to add a new resource but has exceeded his storage quota. I am already handling certain error cases with HTTP status codes (401 for authentication, 403 for authorization and 404 for plain bad request URIs). I looked over the blessed HTTP error codes but none of the 400-417 range seems right to report application specific errors. So at first I was tempted to return my application error with 200 OK and a specific XML payload (ie. Pay us more and you'll get the storage you need!) but I stopped to think about it and it seems to soapy (/shrug in horror). Besides it feels like I'm splitting the error responses into distinct cases, as some are http status code driven and other are content driven.

那么行业建议是什么呢?好的实践(请解释为什么!),并且,从客户端角度来看,REST API中什么样的错误处理可以使客户端代码更容易?


当前回答

如果超出客户端配额,则是服务器错误,在本例中请避免5xx。

其他回答

根据现有的“最佳实践”来建模你的api可能是正确的方法。 例如,Twitter是如何处理错误代码的 https://developer.twitter.com/en/docs/basics/response-codes

为你的API选择正确的HTTP错误代码的一个很好的资源: http://www.codetinkerer.com/2015/12/04/choosing-an-http-status-code.html

文章节选如下:

从哪里开始:

2XX / 3XX:

4XX:

5XX:

不要忘记5xx错误以及应用程序错误。

在这种情况下,409(冲突)怎么样?这假设用户可以通过删除存储资源来解决问题。

否则507(不完全标准)也可以工作。我不会用200,除非你一般用200来表示错误。

我知道这已经是姗姗来迟了,但是现在,在2013年,我们有了一些媒体类型来以通用的分布式(RESTful)方式处理错误。看到盾”。错误”,应用程序/盾。error+json (https://github.com/blongden/vnd.error)和“HTTP api的问题细节”,application/ Problem +json (https://datatracker.ietf.org/doc/html/draft-nottingham-http-problem-05)。

正如其他人指出的那样,在错误代码中包含响应实体是完全允许的。

请记住,5xx错误是服务器端错误,也就是说客户端不能更改其请求的任何内容以使请求通过。如果超出了客户端的配额,那肯定不是服务器错误,所以应该避免5xx。