How to Get the Status Code from an Axios Error in JavaScript
When an HTTP request made with Axios fails, it throws an error. To handle this error correctly, you need to inspect it to determine what went wrong. A common requirement is to get the HTTP status code (like 404 or 500) from the server's response.
This guide will teach you the modern, standard method for reliably getting the status code from an Axios error. You will learn the crucial structure of an Axios error object and the best practice for handling different types of request failures.
The Core Concept: The Structure of an Axios Error
The key to handling Axios errors is understanding that they fall into three main categories. The error object you catch will have different properties depending on what went wrong.
-
The Server Responded with an Error (
error.response): This is the most common case. The request was sent, and the server responded with an error status code (4xx or 5xx). In this case, theerror.responseobject will be defined and will contain all the response details.error.response.data: The response body from the server.error.response.status: The HTTP status code (e.g.,404,500).error.response.headers: The response headers from the server.
-
The Request Was Made, but No Response Was Received (
error.request): This happens when the request is sent, but the client never gets a response back. This is often due to network issues or the server being down. In this case,error.requestwill be defined, buterror.responsewill beundefined. -
Something Else Went Wrong (
error.message): This occurs if there was an issue setting up the request that prevented it from being sent at all (e.g., a configuration error). In this case, neithererror.responsenorerror.requestwill be defined, and you'll only have a genericerror.message.
The Modern Solution (Recommended): A Robust try...catch Block
The best practice is to check for these three cases in order using an if...else if...else structure inside a try...catch block.
For example, we want to make an API call and correctly identify the status code if it fails.
// Problem: How to get the status code when this request fails?
async function makeRequest() {
try {
const response = await axios.get('https://example.com/404');
console.log(response.data);
} catch (error) {
// How do we handle `error` here?
}
}
This is the standard and most robust solution for handling Axios errors.
import axios from 'axios';
async function makeRequest() {
try {
const response = await axios.get('https://example.com/404');
console.log('Success:', response.data);
} catch (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log('--- Server Error ---');
console.log('Status:', error.response.status);
console.log('Data:', error.response.data);
console.log('Headers:', error.response.headers);
} else if (error.request) {
// The request was made but no response was received
console.log('--- Network Error ---');
console.log('Request was made, but no response received:', error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('--- Client Error ---');
console.log('Error:', error.message);
}
}
}
makeRequest();
Because the error.response block is where the server has successfully sent back an error, this is where you can reliably access error.response.status.
A Note on .then().catch()
The exact same error handling logic applies if you are using Promises with .then() and .catch() instead of async/await. The error object passed to the catch callback has the same structure.
axios.get('https://example.com/404')
.then(response => {
console.log('Success:', response.data);
})
.catch(error => {
// The error handling logic is identical to the try...catch block
if (error.response) {
console.log('Status:', error.response.status);
} else if (error.request) {
console.log('Network Error:', error.request);
} else {
console.log('Client Error:', error.message);
}
});
Conclusion
Getting the status code from an Axios error is simple, but doing it safely requires understanding the structure of the Axios error object.
- The HTTP status code is located at
error.response.status. - You must check if
error.responseis defined before trying to access any of its properties. This confirms that the server actually responded. - The most robust error handling pattern is to use an
if...else if...elseblock to check forerror.response,error.request, and other errors in that order.
By following this pattern, you can write resilient code that correctly identifies the type of error and handles it gracefully.