
Axios wraps XMLHttpRequest calls in promises, which means handling errors is mostly about handling rejected promises. When a request fails, Axios rejects the promise with an error object that contains useful properties you’ll want to inspect.
This error object isn’t just a simple message. It has a response property that holds the HTTP response from the server, if any. That response includes status codes, headers, and data. If the request never reached the server (like a network error), response will be undefined.
Understanding this distinction is key because your error handling logic should differ based on whether the server responded or not. For example, a 404 error means your endpoint is wrong or the resource is missing, but a network error might mean the user’s offline or the DNS failed.
axios.get('/user/12345')
.then(response => {
console.log('User data:', response.data);
})
.catch(error => {
if (error.response) {
// Server responded with a status outside 2xx
console.error('Status:', error.response.status);
console.error('Data:', error.response.data);
} else if (error.request) {
// Request was made but no response received
console.error('No response received:', error.request);
} else {
// Something happened setting up the request
console.error('Error:', error.message);
}
});
Another subtlety is that Axios errors also include a config object, the original request configuration. This can be handy for retry logic or logging exactly what went wrong with what parameters.
Beyond the basic properties, the error object also offers a code property, which might contain codes like ECONNABORTED for timeouts. Checking this allows you to distinguish between different network failure modes.
ProCase for iPad 9th/ 8th/ 7th Generation Case 10.2 Inch (2021/2020/2019 Release), 10.2 iPad Case 9th/ 8th/ 7th Gen Cover, Slim Smart Cover with Translucent Hard Shell Back -Black
Now retrieving the price.
(as of June 4, 2026 23:16 GMT +00:00 - More infoProduct prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on [relevant Amazon Site(s), as applicable] at the time of purchase will apply to the purchase of this product.)Common pitfalls in error management
One common pitfall in error management is failing to handle specific HTTP status codes. For instance, while you might have a generic catch for errors, distinguishing between client-side errors (4xx) and server-side errors (5xx) can help you implement more tailored responses. This can be critical for user experience, especially when you can provide feedback based on the error type.
axios.get('/api/data')
.then(response => {
console.log('Data received:', response.data);
})
.catch(error => {
if (error.response) {
switch (error.response.status) {
case 404:
console.error('Resource not found');
break;
case 500:
console.error('Internal server error');
break;
default:
console.error('Error:', error.response.status);
}
} else {
console.error('Error:', error.message);
}
});
Another issue arises from not accounting for the asynchronous nature of these calls. If you are relying on state changes based on the API response, you might inadvertently introduce bugs by not waiting for the promise to resolve before proceeding. Managing state in frameworks like React requires careful consideration of when to set and update state based on API responses.
async function fetchData() {
try {
const response = await axios.get('/api/data');
setData(response.data);
} catch (error) {
console.error('Failed to fetch data:', error);
}
}
Moreover, users often overlook the importance of cleaning up after failed requests. If a request fails, you might still have components that are trying to render based on outdated state or props. Ensuring that your components can handle these cases gracefully especially important to maintain a smooth user experience.
It’s also essential to avoid overloading users with error messages. While it’s important to log errors for debugging, displaying every little failure to the user can create confusion. Instead, consider implementing a logging system that captures errors without overwhelming the user interface.
function logError(error) {
// Send error details to a logging service
axios.post('/api/log', { error });
}
Incorporating user feedback mechanisms can also be beneficial. If a request fails, giving users an option to retry can improve their experience. However, be cautious with how you implement retries to avoid creating an infinite loop of requests that might overwhelm the server or confuse the user.
function handleRetry() {
fetchData().catch(error => {
console.error('Retry failed:', error);
});
}
Lastly, don’t forget to test your error handling thoroughly. Manual testing might not cover all edge cases, so consider writing automated tests that simulate various error scenarios. This will help ensure that your application behaves as expected under different conditions, reducing the likelihood of unexpected failures in production.
Strategies for graceful degradation
Graceful degradation in error handling means ensuring your application can still function, or at least provide a good user experience, even when something goes wrong. The goal is to anticipate failures and design your application flow to minimize disruption.
One effective strategy is to implement fallback mechanisms. For instance, if an API call fails, you might serve cached data or a default response instead of leaving the user in the dark. This keeps the user engaged and provides a semblance of continuity.
async function fetchDataWithFallback() {
try {
const response = await axios.get('/api/data');
setData(response.data);
} catch (error) {
console.warn('Fetching data failed, using fallback:', error);
setData(defaultData); // Use default data
}
}
Another approach is to use a easy to use error message that informs the user of the issue without exposing technical details. A message like “We’re having trouble connecting. Please try again later.” is more appropriate than raw error information.
function showError(message) {
document.getElementById('error-message').innerText = message;
}
It’s also prudent to implement exponential backoff for retries. This means that if a request fails, you wait a bit before trying again, and if it fails again, you wait even longer. This can help reduce the load on your server and give it time to recover.
async function fetchDataWithRetry(retries = 3) {
for (let i = 0; i setTimeout(resolve, Math.pow(2, i) * 1000)); // Exponential backoff
}
}
}
}
Additionally, consider using a service worker to manage requests and caching. This allows your application to serve responses from cache even when offline, providing a seamless experience for users who may have intermittent connectivity.
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});
Monitoring and alerting are crucial parts of graceful degradation. Implement logging that captures error occurrences and user interactions, so you can identify patterns and address recurring issues. This can be done through tools like Sentry or LogRocket.
function logErrorToService(error) {
axios.post('/api/log', { error: error.message, time: new Date() });
}
Finally, always document your error handling strategies and fallback mechanisms. This not only helps current developers understand the system but also aids future maintainers in keeping the user experience smooth and reliable.