Tillitsdone
down Scroll to discover

Error Handling in Axios for Node.js Apps

Master error handling in Axios requests for Node.js applications.

Learn practical patterns, global interceptors, and best practices to build more resilient and user-friendly applications.
thumbnail

A serene abstract representation of network connections featuring interweaving translucent emerald ribbons flowing against a pure black background captured from a top-down perspective high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Error Handling in Axios Requests for Node.js Applications

When building robust Node.js applications, proper error handling isn’t just a best practice—it’s essential. Today, let’s dive into handling errors in Axios requests, making our applications more resilient and user-friendly.

Abstract macro photography of water droplets on a glossy surface rich brown and mahogany with cream colors creating natural patterns shot from a 45-degree angle high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

Understanding Axios Errors

Axios errors might seem daunting at first, but they’re actually quite structured and informative. When a request fails, Axios throws an error object that contains valuable information about what went wrong.

Let’s look at some practical approaches to handle these errors effectively:

1. The Try-Catch Pattern

The most straightforward way to handle Axios errors is using try-catch blocks. Here’s a clean approach:

const fetchUserData = async (userId) => {
try {
const response = await axios.get(`/api/users/${userId}`);
return response.data;
} catch (error) {
if (error.response) {
// Server responded with error status
console.error('Server Error:', error.response.status);
throw new Error(`Failed to fetch user: ${error.response.status}`);
} else if (error.request) {
// Request made but no response received
console.error('Network Error: No response received');
throw new Error('Network error occurred');
} else {
// Something went wrong in request setup
console.error('Request Error:', error.message);
throw new Error('Failed to make request');
}
}
};

Dynamic fluid art composition with swirling umber walnut and iron colors against a light background photographed from a birds-eye view high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

2. Global Error Interceptors

For consistent error handling across your application, Axios interceptors are your best friend:

axios.interceptors.response.use(
response => response,
error => {
if (error.response?.status === 404) {
// Handle 404 errors globally
console.error('Resource not found');
} else if (error.response?.status === 401) {
// Handle authentication errors
console.error('Authentication failed');
}
return Promise.reject(error);
}
);

3. Custom Error Handling Functions

Create reusable error handlers to maintain consistency:

const handleAxiosError = (error) => {
if (axios.isAxiosError(error)) {
const status = error.response?.status;
const message = error.response?.data?.message || error.message;
switch (status) {
case 400:
return 'Invalid request. Please check your data.';
case 401:
return 'Please login to continue.';
case 403:
return 'You don't have permission to access this resource.';
case 404:
return 'The requested resource was not found.';
case 500:
return 'An internal server error occurred. Please try again later.';
default:
return `An error occurred: ${message}`;
}
}
return 'An unexpected error occurred';
};

Best Practices for Error Handling

  1. Always provide meaningful error messages to users
  2. Log detailed error information for debugging
  3. Handle different types of errors appropriately
  4. Implement retry mechanisms for network errors
  5. Use TypeScript for better error typing

Remember, good error handling isn’t just about catching errors—it’s about gracefully managing them to provide a smooth user experience.

Aerial view of ocean waves creating intricate patterns featuring deep blue and white foam textures captured from directly above high-quality ultra-realistic cinematic 8K UHD high resolution sharp and detail

By implementing these error handling patterns, you’ll make your Node.js applications more reliable and maintainable. Your users will thank you, and your future self will appreciate the robust error handling when debugging issues in production.

icons/logo-tid.svg

Talk with CEO

Ready to bring your web/app to life or boost your team with expert Thai developers?
Contact us today to discuss your needs, and let’s create tailored solutions to achieve your goals. We’re here to help at every step!
🖐️ Contact us
Let's keep in Touch
Thank you for your interest in Tillitsdone! Whether you have a question about our services, want to discuss a potential project, or simply want to say hello, we're here and ready to assist you.
We'll be right here with you every step of the way.
Contact Information
rick@tillitsdone.com+66824564755
Find All the Ways to Get in Touch with Tillitsdone - We're Just a Click, Call, or Message Away. We'll Be Right Here, Ready to Respond and Start a Conversation About Your Needs.
Address
9 Phahonyothin Rd, Khlong Nueng, Khlong Luang District, Pathum Thani, Bangkok Thailand
Visit Tillitsdone at Our Physical Location - We'd Love to Welcome You to Our Creative Space. We'll Be Right Here, Ready to Show You Around and Discuss Your Ideas in Person.
Social media
Connect with Tillitsdone on Various Social Platforms - Stay Updated and Engage with Our Latest Projects and Insights. We'll Be Right Here, Sharing Our Journey and Ready to Interact with You.
We anticipate your communication and look forward to discussing how we can contribute to your business's success.
We'll be here, prepared to commence this promising collaboration.
Frequently Asked Questions
Explore frequently asked questions about our products and services.
Whether you're curious about features, warranties, or shopping policies, we provide comprehensive answers to assist you.