When is it appropriate to respond with a HTTP 412 error?

前端 未结 3 1320
不思量自难忘°
不思量自难忘° 2020-12-01 17:33

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 exa

相关标签:
3条回答
  • 2020-12-01 18:18

    If you look at RFC 2616 you'll see a number of request headers that can be used to apply conditions to a request:

    If-Match
    If-Modified-Since
    If-None-Match
    If-Range
    If-Unmodified-Since
    

    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 the PUT to be actioned if the resource has not been modified by someone else since your most recent GET.

    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.

    0 讨论(0)
  • 2020-12-01 18:20

    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.

    0 讨论(0)
  • 2020-12-01 18:33

    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.

    0 讨论(0)
提交回复
热议问题