正确的 HTTP 状态代码到错误的输入
当不报告 200(一切正常)但输入错误时,最佳 HTTP 响应代码是什么?
What is optimal HTTP response Code when not reporting 200 (everything OK) but error in input?
比如,你向服务器提交了一些数据,它会响应你的数据错误
Like, you submit some data to server, and it will response that your data is wrong
使用 500
看起来更像是服务器问题
使用带有警告/错误响应文本的 200
不好(允许缓存并且一切都不好)
使用 204
并且不返回任何内容,这可能很好(但得到很好的支持?)
如果请求的路径(脚本)可用且在适当的位置,则使用 404
是错误的
using 500
looks more like Server Issue
using 200
with warning/error response text is bad (allowing caching and everything is not OK)
using 204
and returning nothing, is maybe good (but well supported?)
using 404
is wrong if requested path (script) is available and in proper place
我们在制作 API 时也遇到了同样的问题.我们正在寻找与 InvalidArgumentException
等效的 HTTP 状态代码.阅读下面的源文章后,我们最终使用了 422 Unprocessable Entity
,它指出:
We had the same problem when making our API as well. We were looking for an HTTP status code equivalent to an InvalidArgumentException
. After reading the source article below, we ended up using 422 Unprocessable Entity
which states:
422(不可处理实体)状态码表示服务器理解请求实体的内容类型(因此 415(不支持的媒体类型)状态码是不合适的),并且请求实体的语法是正确的(因此是 400(错误请求)状态代码不合适)但无法处理包含的指令.例如,如果 XML 请求正文包含格式正确(即语法正确)但语义错误的 XML 指令,则可能会发生这种错误情况.
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.
来源:https://www.bennadel.com/blog/2434-http-status-codes-for-invalid-data-400-vs-422.htm