Common Javascript Mistake: Error Handling with Axios Request

One of the most common JavaScript mistakes is incorrectly handling errors with Axios requests or any other async functions. The code might seem perfectly legit at first glance, but it surprisingly won’t actually catch errors if any occur.

const getSampleData = () => {
    try {
        axios.post('fake-api-endpoint-url', { id: 1 })
            .then((response) => {
                setSampleData(response.data)
            })
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}
JavaScript

Explanation

In this example, the getSampleData function tries to get some sample data from an API using Axios, all wrapped in a try…catch block. But here’s a problem: Axios works in a way where it does its thing in the background, meaning it operates asynchronously. This means that if any errors happen while Axios is doing its job, the try…catch block won’t be able to catch them. So, if something goes wrong during the HTTP request, those errors won’t be handled properly. This can lead to the program not working as expected and possibly crashing.

The Correct Use

There are two simple way to fix it.

Here’s the corrected code using .catch() method:

const getSampleData = () => {
    axios.post('fake-api-endpoint-url', { id: 1 })
        .then((response) => {
            setSampleData(response.data);
        })
        .catch((error) => {
            console.error('Error fetching data:', error);
        });
};
JavaScript

Here’s the corrected code using async/await:

const getSampleData = async () => {
    try {
        const response = await axios.post('fake-api-endpoint-url', { id: 1 });
        setSampleData(response.data);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
};
JavaScript

If possible, I personally highly recommend using async/await over the first method. The latter slightly increases readability and makes it a bit easier to understand.

Leave a Reply

Your email address will not be published. Required fields are marked *