18
votes

The definition of the 502 Bad Gateway status code is:

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.

Is it an appropriate status code to respond with if the error was caused by the database? Despite the fact that the definition of the 500 Internal Server Error status code doesn't state that the error has to be internal, I don't like using it when the error is external.

Can the web server be considered to be a gateway or a proxy, since it is performing tasks other than communicating with the database, such as making calls to other APIs and services?

2
The database is internal to your website, and I wouldn't consider a web server that also renders HTML, processes user input, etc. a proxy or gateway.Colonel Thirty Two

2 Answers

24
votes

No, I don't think an HTTP 502 Bad Gateway error is appropriate when a database error occurs.

HTTP errors say something about the HTTP protocol. This specific error indicates a server is trying to relay the HTTP request, but the upstream server did not respond correctly.

Your web application communicating with a database server is outside the realm of HTTP and any errors should be wrapped in the generic HTTP 500 Internal server error response code.

2
votes

There is no reference for the Database error status code. You can use 500 Internal Server Error as a response.