对于自定义错误,我应该使用什么 HTTP 状态代码? [英] What HTTP status code should I use for custom errors?

查看:23
本文介绍了对于自定义错误,我应该使用什么 HTTP 状态代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要返回有关错误的信息,例如:客户的联系人不能超过 3 个字段作业为空超出操作限制.

I need to return information about errors like: customer can't have more than 3 contacts, field Job is empty, limit of operations was exceeded.

我需要用自己的状态代码发送每个错误吗?
我可以对所有这些错误使用 400 BadRequest 吗?

Do I need send each error with own status code?
Can I use 400 BadRequest for all those errors?

推荐答案

对于所有这些错误,我可以使用 400 BadRequest 吗?

Can I use 400 BadRequest for all those errors?

当然.

这曾经有点可疑,因为 RFC 2616 将 400 Bad Request 定义为:

This used to be a bit questionable, because RFC 2616 defined 400 Bad Request as:

由于格式错误,服务器无法理解请求句法.客户端不应该重复请求修改.

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

然而,通常没有更适用的更好的状态,所以它经常被用作最合适的.

However, there often wasn't a more applicable better status, so it was often used as the best-fit.

随着 RFC 7231 废弃 RFC 2616 并为 400 提供更广泛的定义,这一点已经改变:

This has changed with RFC 7231 obsoleting RFC 2616 and giving a broader definition to 400:

400(错误请求)状态代码表示服务器无法或由于某些被认为是客户端错误(例如,格式错误的请求语法、无效的请求消息帧,或欺骗性请求路由).

The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).

因为被认为是客户端错误的东西"涵盖了许多罪过,所以现在更明确地适用.

Because "something that is perceived to be a client error" covers a multitude of sins, it's now more explicitly applicable.

当然,如果另一个 4xx 代码确实匹配得更好(例如,404 用于与不存在的事物相关的请求 [消息中的 ID 未找到匹配项]),那么它是更好的选择.

Of course, if another 4xx code does match better (e.g. 404 for a request that relates to something that doesn't exist [an ID in the message doesn't find a match]), then it is the better option.

这篇关于对于自定义错误,我应该使用什么 HTTP 状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆