axios error.response is undefined on network-level failure
0 reputation · 10 May 2022, 12:53 UTC
0 reputation · 10 May 2022, 12:53 UTC
Centralize axios error inspection in a response interceptor so status-dependent logic runs only when an HTTP response exists, while network-level failures surface without a secondary TypeError.
Axios leaves error.response undefined for DNS failures, connection refused, and other network-level errors. Reading error.response.status directly throws before fallback logic can run. Recent axios versions favor AbortController over the deprecated CancelToken, and mixing both cancellation styles is unpredictable.
It is unsettled whether an interceptor should check error.response first, use error.code and error.request as discriminators, or treat AbortController cancellation as a separate failure class during an upgrade.
Should error.response.status be accessed with optional chaining or an explicit undefined check?
Are error.code and error.request reliable for distinguishing network failures across Node.js and browsers?
How should cancellation errors from AbortController be separated from network errors without using CancelToken?
error.response is undefined because the request never produced an HTTP response. DNS failures, connection refused, timeouts, and aborts are transport-level rejections; Axios still rejects with an AxiosError, but leaves response unset. Reading error.response.status before confirming the object exists throws TypeError and blocks fallback logic.
axios.interceptors.response.use(
(response) => response,
(error) => {
if (!error.isAxiosError) {
return Promise.reject(error);
}
if (error.response) {
const status = error.response.status;
// status-dependent logic runs only here
} else {
if (isCanceledError(error)) {
return Promise.reject(new Error('Request canceled'));
}
// network-level failure: DNS, refused, timeout, etc.
}
return Promise.reject(error);
}
);
function isCanceledError(error) {
const message = String(error.message ?? '').toLowerCase();
return message.includes('canceled') || message.includes('abort');
}
Prefer an explicit `if (error.response)` guard over optional chaining for branching. `error.response?.status` is safe for a single read, but an explicit guard makes the missing-response branch clearer in shared error handling.
Do not mix legacy CancelToken with AbortController. Pass `signal` from `new AbortController()` into the Axios request and call `controller.abort()` when needed. Check cancellation in the interceptor before any response-status logic.
Missing diagnostic detail: which Axios version and runtime are you targeting? Canceled-error detection changes by version, so this determines whether a message check or a version-specific property check is appropriate.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.