Axios Handling 502 Bad Gateway Proxy Errors
When an upstream proxy returns a 502 Bad Gateway error,
the Axios HTTP client treats the response as a rejected Promise by
default. Because an HTTP response was successfully received—even though
it indicates a gateway failure—Axios generates an
AxiosError containing the complete response object from the
proxy, rather than treating the failure as an unreached network
drop.
Default Rejection Mechanism
By default, Axios evaluates responses using its internal
validateStatus configuration, which resolves promises only
for HTTP status codes in the 2xx range
(status >= 200 && status < 300).
When a proxy server fails to receive a valid response from the origin
server and returns a 502 Bad Gateway:
- The request promise is rejected immediately.
- An
AxiosErroris thrown with the messageRequest failed with status code 502. - Execution flows to the nearest
.catch()block ortry...catchstatement.
Anatomy of the 502 Axios Error Object
Unlike low-level network failures (such as ECONNREFUSED
or DNS resolution failures) where no HTTP response is received, a 502
error originated by a proxy provides a structured response.
The caught error object contains three primary properties:
error.response: Fully defined. Contains the response generated by the proxy:error.response.status: The integer502.error.response.statusText:"Bad Gateway".error.response.data: Any HTML or JSON error payload returned by the proxy.error.response.headers: Headers sent directly by the proxy server.
error.request: The underlyinghttp.ClientRequest(Node.js) orXMLHttpRequest(browser) instance.error.config: The original Axios configuration options used to dispatch the request.
Handling the 502 Error in Code
To properly capture and process a 502 error returned by a proxy,
inspect error.response:
try {
const response = await axios.get('https://api.example.com/data', {
proxy: {
host: 'proxy.internal',
port: 8080
}
});
console.log(response.data);
} catch (error) {
if (axios.isAxiosError(error)) {
if (error.response) {
// The proxy returned a 502 response
console.error(`Status: ${error.response.status}`);
console.error('Proxy Error Payload:', error.response.data);
} else if (error.request) {
// The proxy could not be reached at all
console.error('No response received from proxy.');
}
} else {
console.error('Unexpected error:', error);
}
}Modifying Status Code Validation
If your application needs to handle 502 responses within the
.then() chain instead of the .catch() block,
you can override the validateStatus property in the request
configuration:
const response = await axios.get('https://api.example.com/data', {
validateStatus: function (status) {
// Resolve successfully for 2xx and 502 status codes
return (status >= 200 && status < 300) || status === 502;
}
});
if (response.status === 502) {
// Handle upstream gateway failure manually
console.warn('Received 502 from proxy, proceeding with fallback.');
}