Check Axios Errors Using axios.isAxiosError
When handling exceptions in web applications, distinguishing between
network failures, standard JavaScript runtime errors, and specific HTTP
response errors is critical for reliable error handling. Axios provides
a built-in utility function called axios.isAxiosError that
checks whether a caught object is an Axios-specific error. This guide
demonstrates how to use axios.isAxiosError in both
JavaScript and TypeScript to safely inspect and handle HTTP error
responses.
Understanding
axios.isAxiosError
In JavaScript and TypeScript, caught errors in a
try...catch block have an unknown type by default. The
axios.isAxiosError method is a type guard that checks for
the internal isAxiosError: true flag attached to all errors
generated by Axios. It returns true if the object is an
Axios error and false otherwise.
Using this method prevents runtime crashes when trying to access
Axios-specific properties—such as error.response or
error.request—on generic errors.
Basic Usage in JavaScript
To check for an Axios error, pass the caught error directly into
axios.isAxiosError():
import axios from 'axios';
async function fetchUserData(userId) {
try {
const response = await axios.get(`https://api.example.com/users/${userId}`);
return response.data;
} catch (error) {
if (axios.isAxiosError(error)) {
// The error is specific to Axios
console.error('Axios error message:', error.message);
if (error.response) {
console.error('Status code:', error.response.status);
console.error('Response data:', error.response.data);
}
} else {
// Generic JavaScript or unexpected error
console.error('Unexpected error:', error);
}
}
}Using
axios.isAxiosError in TypeScript
In TypeScript, axios.isAxiosError serves as a custom
type guard (error is AxiosError<T>). When the check
evaluates to true, TypeScript automatically narrows the
type of error, granting full type safety and autocompletion
for Axios properties.
import axios, { AxiosError } from 'axios';
interface ApiErrorResponse {
message: string;
code: number;
}
async function sendData(payload: object) {
try {
const response = await axios.post('https://api.example.com/data', payload);
return response.data;
} catch (error) {
if (axios.isAxiosError<ApiErrorResponse>(error)) {
// TypeScript knows 'error' is AxiosError<ApiErrorResponse>
if (error.response) {
// Access strongly typed response data
console.error(`API Error (${error.response.status}):`, error.response.data.message);
} else if (error.request) {
// The request was made, but no response was received
console.error('Network Error: No response received from server.');
} else {
// Error setting up the request
console.error('Request setup error:', error.message);
}
} else {
// Handle non-Axios errors
console.error('Non-Axios error occurred:', error);
}
}
}Inspecting Axios Error States
Once confirmed as an Axios error, you can inspect three distinct error categories:
- Server Response Errors
(
error.response): The server responded with a status code outside the2xxrange (e.g., 404, 500). Containsstatus,headers, anddata. - Network/Timeout Errors
(
error.request): The HTTP request was initiated, but no response was received (e.g., connection lost, CORS failure, timeout). - Configuration Errors (
error.message): An issue occurred while setting up the request before it was sent.
Why Not Use
instanceof AxiosError?
While error instanceof AxiosError works in many
scenarios, axios.isAxiosError(error) is the recommended
approach. The instanceof check can fail if your project
bundles multiple versions of Axios, runs across different execution
contexts (such as iframes or Node.js VM modules), or handles serialized
error objects. axios.isAxiosError relies on property
validation rather than prototype inheritance, making it more
resilient.