gpt4 book ai didi

HTTP 状态代码 4xx 与 5xx

转载 作者:可可西里 更新时间:2023-11-01 15:24:27 24 4
gpt4 key购买 nike

我正在创建一个 REST API,发现在某些情况下很难选择正确的 HTTP 状态代码来返回。

假设我期望某个值,当它不存在时我无法执行某个任务并返回错误。由于缺少值,服务器无法处理该请求,但它是客户端发送的,格式良好但不完整,in. Would it be best to return a 4xx or a 5xx错误?

最佳答案

坚持标准!

向客户端发送哪个 HTTP 状态代码由您决定,但您确实应该遵守标准RFC 7231是 HTTP/1.1 协议(protocol)内容和语义的当前引用。在 HTTP 协议(protocol)之上创建 API 时必读。

4xx5xx 状态码

使用 4xx 客户端错误状态代码和 5xx 服务器错误状态代码:

6.5. Client Error 4xx

The 4xx (Client Error) class of status code indicates that the clientseems to have erred. Except when responding to a HEAD request, theserver SHOULD send a representation containing an explanation of theerror situation, and whether it is a temporary or permanentcondition. These status codes are applicable to any request method.User agents SHOULD display any included representation to the user.

6.6. Server Error 5xx

The 5xx (Server Error) class of status code indicates that the serveris aware that it has erred or is incapable of performing therequested method. Except when responding to a HEAD request, theserver SHOULD send a representation containing an explanation of theerror situation, and whether it is a temporary or permanentcondition. A user agent SHOULD display any included representationto the user. These response codes are applicable to any requestmethod.

你应该使用哪个状态码

对于您在问题中提到的情况,您可以使用 400422(来自 WebDAV,一种 HTTP 扩展):

6.5.1. 400 Bad Request

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

11.2. 422 Unprocessable Entity

The 422 (Unprocessable Entity) status code means the serverunderstands the content type of the request entity (hence a415(Unsupported Media Type) status code is inappropriate), and thesyntax of the request entity is correct (thus a 400 (Bad Request)status code is inappropriate) but was unable to process the containedinstructions. For example, this error condition may occur if an XMLrequest body contains well-formed (i.e., syntactically correct), butsemantically erroneous, XML instructions.

连同状态代码,请确保您发送的表示形式(例如 JSON 或 XML)包含对响应负载中错误情况的解释。看看 RFC 7807 ,它描述了 HTTP API 问题详细信息的标准。

一个很棒的决策图

有关更多详细信息,请查看此 decision chart来自拉克斯堡:


状态码大致分为三类:

HTTP status codes categories


从这里开始:

HTTP status codes


选择2xx3xx状态码:

HTTP 2xx and 3xx status codes


选择 4xx 状态码:

HTTP 4xx status codes


选择5xx状态码:

HTTP 5xx status codes

关于HTTP 状态代码 4xx 与 5xx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39636795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com