我有一个返回 Voucher
对象的 api 端点。
凭证是从第三方获取的。
我们会检查/验证某些条件,例如过期日期。
因此,如果客户端应用程序请求 /voucher/1234
从第三方检索 ID 为 1234 的凭证。
如果过期日期是<现在,我们需要返回一个错误。
我想返回标准的 HTTP 错误。
哪个最合适?
我最初以为是 412,但现在我不确定了。
最佳答案
当服务器不满足请求 header 中提供的先决条件之一(If-Match、If-Modified-Since 等)时,将使用 HTTP 412。
非常通用的方法是在无效字段上返回 HTTP 400 + 特定错误消息。
然而,越来越多的 populer API 开始使用 HTTP 扩展来更精细地向客户端反馈错误。 Twitter 和 GitHub 使用 WebDAV HTTP 扩展中定义的 HTTP 422 不可处理实体。 HTTP 422 says that :
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.
您的服务器了解用户想要做什么,也了解数据包含什么,只是不会让您那样做。所以,Http 422 看起来很适合你。
关于http - 根据我们域中定义的规则,Http 状态代码 412 是否适合错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20287724/