什么时候适合响应 HTTP 412 错误?
我不清楚什么时候应该或不应该返回 HTTP 412:先决条件失败,Web 服务错误?我正在考虑在验证数据时使用它。例如,如果客户端 POST 的 XML 数据并且该数据缺少必需的数据元素,则以 412 和错误描述进行响应。
这是否符合 HTTP 412 响应的精神,还是应该使用其他内容(例如另一个 http 错误代码或 Web 应用程序异常)?
It is unclear to me when you should and should not return a HTTP 412: Precondition Failed, error for a web service? I am thinking of using it when validating data. For example, if a client POST's XML data and that data is missing a required data element, then responding with a 412 and a description of the error.
Does that align with the spirit of responding with an HTTP 412, or should something else be used (e.g. another http error code or web application exception)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您查看 RFC 2616,您会看到许多请求标头,这些标头可以用于将条件应用于请求:
这些标头包含“前提条件”,允许客户端告诉服务器仅在满足某些条件时才完成请求。例如,您使用
PUT
请求来更新资源的状态,但您只希望在该资源自此以来未被其他人修改过时才执行PUT
您最近的GET
。当这些前提条件失败时,通常会使用响应状态代码
412
(前提条件失败)。您的示例听起来像是无效的请求(即客户端提交了由于缺少值而无效的数据)。在我看来,状态代码
400
(错误请求)在这里更合适。If you look at RFC 2616 you'll see a number of request headers that can be used to apply conditions to a request:
These headers contain 'preconditions', allowing the client to tell the server to only complete the request if certain conditions are met. For example, you use a
PUT
request to update the state of a resource, but you only want thePUT
to be actioned if the resource has not been modified by someone else since your most recentGET
.The response status code
412
(Precondition Failed) is typically used when these preconditions fail.Your example sounds like an invalid request (i.e. the client has submitted data that is invalid because of missing values). A status code of
400
(Bad Request) is more appropriate here IMO.412 是为请求有条件且条件不满足的情况保留的。
对于您的用例,422 Unprocessable Entity 是一个很好的匹配。
412 is reserved for cases where the request is conditional, and the condition isn't met.
For your use case, 422 Unprocessable Entity is a good match.
最好的选择是避免 412。实际上,我使用过的大多数 Web 服务都会发送 400 代码(错误请求)。许多框架也内置了对 400 的支持,您的客户会喜欢更常见的错误代码。很多时候,特别是对于 REST 接口,会返回一个简单的“消息”或“错误”元素以及描述。
Your best bet would be to avoid 412. In practice most web services that I've used send a 400 code (Bad Request). A lot of frameworks have built-in support for 400 too and your clients will appreciate a more common error code. Often times, especially with REST interfaces, a simple "message" or "error" element is returned with a description.
此问题的发生是由于以下 HTTP 标头
首先通过以下代码检查当前请求的这些 HTTP 标头值
,如下所示。
获取这些 HTTP 标头值后,更改这些 HTTP 标头值以处理请求并处理 412 HTTP 代码错误
This Problem occur due to following HTTP Header
First check these HTTP header value for present request by following code
That will look like following.
After getting these HTTP header value change these HTTP header value to handle request and handle 412 HTTP code Error