当不报告 200(一切正常)但输入错误时,最佳 HTTP 响应代码是什么?
比如,你向服务器提交一些数据,它会响应你的数据有误
使用 500
看起来更像是服务器问题
将 200
与警告/错误响应文本一起使用是错误的(允许缓存但一切都不正常)
使用 204
并且不返回任何内容,这可能很好(但得到很好的支持?)
如果请求的路径(脚本)可用且位置正确,则使用 404
是错误的
最佳答案
我们在制作 API 时也遇到了同样的问题。我们正在寻找等同于 InvalidArgumentException
的 HTTP 状态代码。阅读下面的源文章后,我们最终使用了 422 Unprocessable Entity
,其中指出:
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
关于validation - 错误输入应该使用什么 HTTP 状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7939137/