非严重服务器错误的 HTTP 状态代码

HTTP status code for noncritical server errors

如果出现非关键服务器错误,我 return 应该在我的 API 中使用哪个 HTTP 状态代码?

例如,调用了 SomeMethod,但失败了,原因是传递空值,或者尝试访问数据库时出现一些错误,等等。

我想过 500 代码,但是当服务器根本不工作时使用它, 而 SomeMethod 只有在一切正确的情况下才有效。

当然,响应正文包含错误及其描述。

由于 "non-critical error" 没有特定的 HTTP 代码,所以我只能告诉你我的意见,即 - 只需使用 200 并打印类似异常的响应。

正如您在评论中所说 - 您能够优雅地处理内部错误,所以只需向客户端抛出一个异常来解释他的请求失败的原因("why" 可以类似于 "internal database error").

如果这些“非严重错误”是由客户端的错误输入(例如,错误的数据类型)引起的,那么您应该使用客户端错误状态代码 400(错误请求).

这是来自 standard 的描述:

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).