paint-brush
Axios: What to Do When Something Goes Wrongby@theBenForce
642 reads
642 reads

Axios: What to Do When Something Goes Wrong

by Ben ForceFebruary 2nd, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

The Axios package is a Node.js library for making API calls. It's easy to use, well documented, uses promises, and it works in browsers too. The main complaint from other developers is that when an error response is returned, it's not obvious how to get information about it.
featured image - Axios: What to Do When Something Goes Wrong
Ben Force HackerNoon profile picture

If you search for libraries to make API calls from Node.js, chances are you'll run into the Axios package. It's easy to use, well documented, uses promises, and it works in browsers too.

When Things Go Wrong

The main complaint from other developers is that when they make a request and an error response is returned, it's not obvious how to get information about the error. Usually, this happens when they don't catch the exception and expect the response to include the status code.


const response = await axios.get(SOME_URL);

if(response.status === 404) {
    console.error(`${SOME_URL} not found!`);
}


This approach won't work because Axios, by default, throws an exception for any status code that isn't 2xx. There is a workaround though.

Making It More Responsive

You can tell Axios that you want to see every response regardless of if it's an error or not using the request options. You need to provide a validateStatus method that always returns true. This method is passed to Axios in the request options.


const response = await axios.get(SOME_URL, {
    validateStatus: () => true,
});

if(response.status === 404) {
    console.error(`${SOME_URL} not found!`);
}


Now, you'll reach the if statement as expected.

There's a .catch()

If you look at the Axios documentation on error handling, you're supposed to catch the exception that it throws. You can use the response property on the exception to determine what status was returned. Finally, you can gracefully return some value and continue work.


const contents = await axios.get(SOME_URL)
    .then((response) => response.data)
    .catch((error) => {
        if(error.response?.status === 404) {
            console.error(`Could not find ${SOME_URL}`, response.data);
            return undefined;
        }

        // Something unexpected
        throw error;
    });

if(!contents) return;

Summary

You've seen a couple of ways to deal with error responses when making HTTP calls with Axios.


The important thing to remember is that it will throw an error for non-2xx responses, and the response property on the thrown exception will contain all of the data that you would normally get back (status, body, etc.).