Skip to content
Advertisement

How to get catch error 404 error in Axios?

I have this snippet of code (part of a function), notice the “BadURL” at the end of the URL:

import axios from “axios”;

try {
  return axios.post("http://localhost:5000/api/featureFlagBadURL", {
    flagName: "newJqueryAjaxListener",
    defaultValue: "false",
  });
} catch (error) {
  return { data: 'false' }
}

But canno’t get into the catch block, says:

(node:7676) UnhandledPromiseRejectionWarning: Error: Request failed with status code 404

I can catch the error only if i wrap the function call itself outside the class

Advertisement

Answer

Axios.post(...) is an asynchronous call that returns a promise, that statement doesn’t fail, and even if it does, it’s not because of the HTTP request failing.

What you need to use is the .then() and .catch() methods of the returned promise to handle the request.

return axios.post("http://localhost:5000/api/featureFlagBadURL", {
    flagName: "newJqueryAjaxListener",
    defaultValue: "false"
}).then((results) => {
    console.log('yay', results);
}).catch((error) => {
    console.log('oops', error);
});

Another alternative is to use async await.

async function handler() {
    try {
        const results = await axios.post("http://localhost:5000/api/featureFlagBadURL", {
            flagName: "newJqueryAjaxListener",
            defaultValue: "false",
        });
        console.log('yay', results);
    }
    catch (error) {
        console.log('oops', error);
        return { data: 'false' };
    }
})
Advertisement