404错误或400错误?

36

假设我们有以下的REST调用:

GET api/companies/5 

(以id 5获取公司)

如果公司“5”不存在,通常会返回404 Not Found响应。

但是现在,让我们来看一下这个调用:

GET api/companies/5/invoices/10 

(从公司 5 获取发票 10)

现在,如果公司“5”不存在,我们是否仍然返回 404 Not Found?还是只有在最外层的资源找不到时(在本例中是发票10),才会返回404?

也许使用 Bad Request 更好一些吗?


1
最好的做法是使用自定义错误消息处理404错误,将不美观的错误信息隐藏起来对用户更友好。 - Charlie
严格来说,应该是404。但响应正文可能包含任何内容。完整的响应将驱动下一步操作。 - Pankaj Jangid
2个回答

39

404是最佳的响应。 根据HTTP RFC,http://www.ietf.org/rfc/rfc2616.txt

400 Bad Request表示:

由于语法错误,服务器无法理解请求。

而404则表示:

服务器未找到与请求URI匹配的内容。

整个URI是您的资源标识符,并且您没有找到特定标识符的匹配资源。


6

404错误可能会引起混淆——是资源丢失还是URL实际上不正确?

我个人会选择使用422状态码:

   The 422 (Unprocessable Entity) status code means the server
   understands the content type of the request entity (hence a
   415(Unsupported Media Type) status code is inappropriate), and the
   syntax of the request entity is correct (thus a 400 (Bad Request)
   status code is inappropriate) but was unable to process the contained
   instructions.  For example, this error condition may occur if an XML
   request body contains well-formed (i.e., syntactically correct), but
   semantically erroneous, XML instructions.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接