如果 REST API 方法失败,我应该返回 200、400 还是 500 HTTP 状态消息?
当用户向我的 API 提交无效数据(通常通过 Javascript + JSON)时,我想知道我应该使用哪个 HTTP 响应代码回复与.
我是否应该返回包含错误的 HTTP 200 响应,或者我的服务器是否应该响应 400 或 500 错误,因为请求实际上因某些错误数据而未能通过我的验证?
似乎 400 错误是正确的选择,因为“4xx 类状态代码适用于客户端似乎犯了错误的情况” - wikipedia
然而,需要记住的一件事是,大多数人使用像 jQuery 这样的框架,当 AJAX 请求以除200.
When a user submits invalid data to my API (usually via Javascript + JSON), I am wondering which HTTP response code I should reply with.
Should I return a HTTP 200 response with the errors - or should my server respond with a 400 or 500 error since the request actually failed my validation because of some bad data?
It seems like a 400 error is the way to go since "The 4xx class of status code is intended for cases in which the client seems to have erred" - wikipedia
However, one thing to keep in mind is that most people use a framework like jQuery which requires you to specify an alternate callback when AJAX requests respond with any status code other than a 200.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在jquery ajax调用中使用statusCode:
use statusCode in jquery ajax calling:
这一直是一个巨大的困境。事实是,由开发团队选择什么,两者都是有效的,并且如果处理正确,两者都会正常工作。我希望我们能有一个标准的做事方式。但不幸的是,硬币的两面都有争论,要么是完整的 400 状态代码,带有 json 错误解释“业务规则错误”,要么是 200 状态代码,带有 json 指示存在业务错误,即 ok->false (就像 Slack )
仅供参考。-我见过的大多数客户端库都会将状态代码 != 200-299 视为错误。
This has been a huge dilema forever. The truth is that it up to the dev team what to chose, both are valid and both will work fine if handled correctly. I wish we could have a standard way of doing things. But unluckily there are arguments on both sides of the coin, either go full 400 status code with json error explaining the "business rule error" or 200 status code with json indicating there was a business error, i.e. ok->false (Like Slack does with its API.)
Just FYI.- most of the client side libraries I've seen will treat a status code != 200-299 as an error.