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

查看:535
本文介绍了对于一般不成功的请求(不是错误),什么是适当的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 Services Cookbook

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:


某些网络服务的一个常见错误是返回反映成功的状态
代码(状态代码从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天全站免登陆