Prevent Axios from Throwing on 4xx and 5xx Codes
By default, Axios throws an error and rejects the Promise whenever an
HTTP request returns a status code outside the 2xx range. To prevent
Axios from throwing exceptions on 4xx (client error) and 5xx (server
error) response codes, you must configure the
validateStatus property. This article explains how to use
validateStatus in Axios to treat all HTTP status codes as
resolved responses.
The
validateStatus Configuration
The validateStatus option is a function that defines
whether to resolve or reject the promise for a given HTTP response
status code. By default, Axios defines this setting as:
validateStatus: function (status) {
return status >= 200 && status < 300; // default
}If the function returns true, the promise resolves
successfully. If it returns false, Axios rejects the
promise and triggers the .catch() block or throws an
exception in an async/await try-catch block.
How to Prevent Exceptions on All Status Codes
To prevent Axios from throwing errors on any HTTP response code,
configure validateStatus to always return
true.
1. In a Single Request
You can pass validateStatus directly in the request
configuration object:
const axios = require('axios');
async function fetchData() {
const response = await axios.get('https://api.example.com/data', {
validateStatus: function (status) {
return true; // Always resolve, even for 4xx and 5xx
}
});
console.log(`Status Code: ${response.status}`);
console.log(`Response Data:`, response.data);
}Using an arrow function shorthand:
const response = await axios.get('https://api.example.com/data', {
validateStatus: () => true
});2. In an Axios Instance
If you want this behavior applied across multiple requests, configure it when creating an Axios instance:
const apiClient = axios.create({
baseURL: 'https://api.example.com',
validateStatus: () => true
});
// This request will not throw on 404, 500, etc.
const response = await apiClient.get('/users/invalid-id');
console.log(response.status); // e.g., 4043. Setting Globally via Defaults
You can also set this globally for all default Axios requests:
axios.defaults.validateStatus = () => true;Handling Specific Status Ranges
If you only want to allow specific error codes (such as handling 404 manually while still throwing on 500 server errors), you can customize the return condition:
const response = await axios.get('https://api.example.com/data', {
validateStatus: function (status) {
// Resolve for all status codes below 500 (2xx, 3xx, 4xx)
return status < 500;
}
});Important Considerations
When using validateStatus: () => true:
- Axios will not execute the
.catch()block for 4xx and 5xx responses. - Network-level errors (such as connection timeouts, DNS resolution failures, or offline errors) will still throw exceptions because no HTTP response was received.
- You must manually check
response.statusin your application logic to determine whether the request was successful.