对于一般不成功的请求(不是错误),合适的 HTTP 状态代码响应是什么? [英] What is the appropriate HTTP status code response for a general unsuccessful request (not an error)?

查看:35
本文介绍了对于一般不成功的请求(不是错误),合适的 HTTP 状态代码响应是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 RESTful API,它将处理许多用户交互,包括使用存储的信用卡下订单.

I'm creating a RESTful API that will process a number of user interactions, including placing orders using stored credit cards.

如果订单成功,我将返回 200 OK,如果订单请求格式错误或无效,我将返回 400 Bad Request.但是在订单的实际处理过程中出现问题应该怎么退货?

In the case of a successful order, I'm returning a 200 OK, and in the case where the order request is malformed or invalid I'm returning a 400 Bad Request. But what should I return if there is a problem during the actual processing of the order?

  1. 客户端向服务器POSTS 订单以获取用户资源.如果用户不存在,则返回 404 Not Found.
  2. 订单格式和信息经过验证.如果无效,则返回 400 Bad Request.
  3. 订单已处理.如果订单成功,则为订单返回 201 Created.如果遇到意外错误,将返回 500 服务器错误.

最后一步是问题 - 如果订单由于任何其他原因没有完成,我应该返回什么?可能的情况包括:

The last step is the problem - what do I return if the order doesn't complete for any other reason? Possible scenarios could include:

  • 产品已售罄
  • 达到用户最大下单限额
  • 信用卡交易失败(资金不足等)

这似乎不适合 400 或 500.如果没有更好的代码,我可以将其视为 400 - 根据业务规则,请求无效.只是看起来不太准确.

This doesn't seem like it would be appropriate for either a 400 or 500. If anything I could see it as a 400 if there's no better code - the request was invalid according to the business rules. It just doesn't seem accurate.

还发现 同一主题的现有讨论.那里的所有答案似乎都指向对此类违规使用状态代码,并在使用 400、409 或 422 扩展名之间进行了一些讨论.

Also found this existing discussion of the same topic. All of the answers there seem to point to using status codes for this type of violation, with some discussion between using 400, 409, or the 422 extension.

推荐答案

对于业务规则,您应该使用 400.如果订单未被接受,请勿返回 2xx.HTTP 是一种应用程序协议,永远不要忘记这一点.如果您返回 2xx,则客户端可以假定订单已被接受,无论您在正文中发送任何信息.


来自 RESTful Web 服务手册:

You should use 400 for business rules. Don't return 2xx if the order was not accepted. HTTP is an application protocol, never forget that. If you return 2xx the client can assume the order was accepted, regardless of any information you send in the body.


From RESTful Web Services Cookbook:

某些 Web 服务常犯的一个错误是返回状态反映成功的代码(状态代码从 200 到 206 和从 300到 307),但包括描述错误情况的消息正文.这样做可以防止 HTTP 感知软件检测到错误.为了例如,缓存会将其存储为成功响应并将其提供给后续客户,即使客户可能能够成功请求.

One common mistake that some web services make is to return a status code that reflects success (status codes from 200 to 206 and from 300 to 307) but include a message body that describes an error condition. Doing this prevents HTTP-aware software from detecting errors. For example, a cache will store it as successful response and serve it to subsequent clients even when clients may be able to make a successful request.

我将让您在 4xx 和 5xx 之间做出决定,但您应该使用错误状态代码.

I'll leave it to you to decide between 4xx and 5xx, but you should use an error status code.

这篇关于对于一般不成功的请求(不是错误),合适的 HTTP 状态代码响应是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆