Explain Codes LogoExplain Codes Logo

Axios handling errors

javascript
axios
error-handling
interceptors
Nikita BarsukovbyNikita Barsukov·Oct 15, 2024
TLDR

Landing on Axios errors? Let's weave through them using .catch() and hop aboard the error object. Understand the following pit stops: error.response (server responses), error.request (cue the crickets, because no one responded), and error.message (honest confession: we messed up the request setup). Here's how we'll tour:

axios.get('/endpoint') .then(response => console.log(response.data)) // Look ma, no errors! .catch(error => { let errMsg = error.response ? `Status: ${error.response.status}, Data: ${error.response.data}` // Server gave us a cold shoulder : error.request ? 'No response received' // Are we...lonely? : `Request setup error: ${error.message}`; console.error(`Tour guide, Axios, stumbles: ${errMsg}`); // Error? Time for some introspection! });

This treasure route maps your way around common Axios hiccups.

Playing with interceptors: Centralized error handling

Ever had a tour guide who manages all the roadblocks and hiccups smoothly? Welcome Axios interceptors! They help you centralize error handling. No need for .catch() sneak around your code anymore.

axios.interceptors.response.use(response => response, error => { if (!error.response) { console.error('Made a call, but echo was the only reply', error.request); // Playing Marco Polo with server! } else if (!error.response.data) { console.error('Hello?? Any data out there?', error.response); // Data went on a vacation } else { console.error('Oopsie! Server goofed up:', error.response); // Server's blunders } return Promise.reject(error); // Let's replay this in higher leagues! });

Ahoy! Did you see that rejected promise? It's your lucky charm, helping you handle future promises at the call site with a .catch() block.

Async/await: Simplifying error handling

Love the simplicity of async/await in dealing with asynchronous code? Wrap them into a cozy little blanket known as try/catch block! It will handle your Axios errors in style:

async function fetchTourDetails() { try { const response = await axios.get('/endpoint'); console.log(response.data); // Fancy, error-free data! } catch (error) { console.error('Oops! Stumbled while fetching data', error); // Fetching or fumbling? } }

Try this pattern, it's a game changer for readable and maintainable code landscapes!

Acceptable response codes: Personalized rejection

Remember the fussy eaters who would only eat what they prefer? In our code world, we call them validateStatus option. They decide what Axios should consider a successful response:

axios.get('/endpoint', { validateStatus: function(status) { return status < 500; // Anything under 500? We're cool! } }) .then(response => console.log(response.data)) // Received data? Slurp! .catch(error => console.error(`Well, isn't this awkward. Server's mad at us!`, error)); // Server and us are on a break

With this in place, only certain HTTP status codes will make Axios break up with the promise!

Keeping things DRY with Request.js

Remember our tour guide, Axios? Let create top-notch guide profile in Request.js file! This way, you can implement error handling once, and then just reuse the guide throughout your trip err... I mean, across your application's files:

// Request.js import axios from 'axios'; const request = axios.create({ baseURL: 'https://api.yourdomain.com', /* ... other custom settings ... */ }); request.interceptors.response.use(response => response, error => { // Your central error handling logic // ... handle errors ... return Promise.reject(error); // And, we're back to the drawing board! }); export default request; // Don't forget to make our guide popular!

Now, like a superstar, import this all-around the app, and watch the magic unfold!

Efficient error handling in promise chains

For a roller-coaster ride with multiple promise chains, you can use .then().catch() to handle any loops, dips or scary parts at each step:

axios.get('/step1') .then(response => { console.log('Step 1 completed', response.data); // Step one, and we're having fun! return axios.get('/step2'); }) .then(response => { console.log('Step 2 completed', response.data); // Step two, no clue what's in store }) .catch(error => { console.error('Rollercoaster ride got scary!', error); // Bonkers in promise-land! });

In this ride, an error at any point will make you scream (read: handle) in the single .catch() at the end.

Error object: Understanding and debugging

An error object looks like a puzzle? Fear not! Let's solve it by destructuring:

.catch(({ response, request, message }) => { // Dismantle it, piece by piece! if (response) { console.error(`Server flexing muscles with ${response.status} status:`, response.data); // No road is long with good company, Server isn’t one! } else if (request) { console.error('Error: No response received', request); // Server playing hide and seek? } else { console.error("Server's upset, call setup failed", message); //"Psst! Dear server, get your act together!" } });

Now you know how to debug like a pro!

Debugging with Stylish Log

Error logs are like journals! They record everything that went wrong, helping us understand where we goofed up! Don't forget to log the errors:

.catch(error => { console.error(`Plot Twist: Error!`, error); //"What’s error's favorite spot? The console!" // Maybe consider a logging service for better tracking logService.error(error); });

Error logs are like horoscopes, they help us predict future (problems)!

Using .get method for simple orders

Making GET requests? Let's make it simpler using axios.get. It's straightforward for including error handling:

axios.get('/simple-get') .then(response => console.log('Data:', response.data)) // Hey server, I got your message! .catch(error => console.error('Server's throwing tantrum!', error)); // Can't figure out the server's signals.

Simple, smooth, error-free. That's how we roll!