远程服务器故障时使用哪个 HTTP 状态代码? 500 还是 502?

Which HTTP status code to use upon remote server failure? 500 or 502?

我有一个 API,根据客户的 POST 请求:

  1. 解析客户端的请求
  2. 处理请求中的数据
  3. 向远程服务器发送请求
  4. 收到来自远程服务器的响应
  5. 用响应中的数据做更多的事情
  6. 将数据保存在数据库中
  7. 向客户端发送响应

换句话说,正常的 Web 服务器内容。

如果远程服务器向我发送 500(或任何其他错误),我应该向我的客户端发送 500 Internal Server Error 还是 502 Bad Gateway

来自 RFC 7231,

6.6.3.  502 Bad Gateway

   The 502 (Bad Gateway) status code indicates that the server, while
   acting as a gateway or proxy, received an invalid response from an
   inbound server it accessed while attempting to fulfill the request.

一方面,502 Bad Gateway 看起来是为 "dumb" 服务器设计的,它只是将请求转发到远程服务器,returns 它对客户端的响应,没有很多处理。

另一方面,无法访问远程服务器听起来不像 500 Internal Server Error...更像是 "Remote Server Error"。

我应该使用哪一个? 500502 还是其他?

我会选择 500。

这并不重要 - 两者都是 5xx 系列错误的一部分,意思是 "we screwed up, not you" - 所以到底出了什么问题并不是你 需要 试图传达返回的错误代码。 500 是通用的,易于理解且含义明确,所以我只是使用它而不是使事情过于复杂。

解决您的具体问题。

In one hand, the 502 Bad Gateway looks like this is intended for "dumb" servers that just forwards the request to the remote server, and returns its response to the client, without much processing.

当然这都是惯例,但我想说您的分析相当正确。

In the other hand, to not be able to access the remote server doesn't sound like a 500 Internal Server Error... more like a "Remote Server Error".

我认为这仍然是一个内部服务器错误,只是一个由其他地方的远程服务器引起的内部服务器错误(这可能是您的用户不了解的细节)不需要知道。)