当我的网站 api 由于第 3 方服务而无法执行操作时,我应该发送什么响应

What response do I send when my web api can't perform an action due to 3rd party service

我正在开发用 dotnet 核心编写的 C# Web API。我正在努力处理试图从另一台服务器上的第三方服务检索数据的操作的 return。如果在尝试从上述第 3 方服务获取数据时出现问题,在查看 spec 时对我来说最有意义的 HTTP 响应是 502 Bad Gateway 因为

The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.

但我无法在我的操作中找到 return 的方法。 IActionResult 似乎没有此代码的实现。我的想法是否正确?

Web Api 包含一些您应该尽可能使用的快捷方法,但对于抛出的一些更常见的错误代码,它们只有一些方法。

以下将 return 返回 StatusCode:

return StatusCode(HttpStatusCode.BadGateway);

最常见的 return 是:

return NotFound() // 404
return Ok() //200
return InternalServerError() //500

您应该问问自己是否绝对有必要 return 确切的错误代码。你的前端需要知道吗?如果您已经在 API 中处理异常记录,您可能应该 return 一些更通用的东西,例如 InternalServerError().