HTTP Status Code for External Dependency Error

2019-04-04 00:28发布

问题:

What is the correct HTTP status code to return when a server is having issues communicating with an external API?

Say a client sends a valid request to my server A, A then queries server B's API in order to do something. However B's API is currently throwing 500's or is somehow unreachable, what status code should A return to the client? A 5* error doesn't seem correct because server A is functioning as it should, and a 4* error doesn't seem correct because the client is sending a valid request to A.

回答1:

Since the API relies on something that is not available, its service is unavailable as well.

I would think that the status code 503: Service Unavailable is the best fit for your situation. From the RFC description:

The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.

Granted, the description implies that this status code should be applied for errors on the server itself (and not to signal a problem with an external dependency). However, this is the best fit within the RFC status codes, and I wouldn't suggest using any custom status codes so anyone can understand them.

Alternatively, if your API supports a way of communicating errors (e.g. to tell the user that the ID he supplied is incorrect) you may be able to use this method to tell the user that the dependency is unavailable. This might be a little friendlier and might avoid some bug searching on the user's side, since at least some of the users won't be familiar with any status codes besides 403, 404 and maybe 500, depending on your audience.



回答2:

Did you consider status codes 502 and 504?

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

504 – The server, while acting as a gateway or proxy, 
did not receive a timely response from the upstream server 
specified by the URI (e.g. HTTP, FTP, LDAP) 
or some other auxiliary server (e.g. DNS) it needed to access 
in attempting to complete the request.

Of course, this would require a broad interpretation of "gateway" (implementation of interface A requiring a call to interface B), applied to the application layer. But this could be a nice way to say : "I cannot answer but it's not my fault nor yours".



回答3:

You can refer this link.

HTTP Status 424 or 500 for error on external dependency

503 Service Unavailable looks perfect for the situation.