Ballon Ura
Ballon Ura

Reputation: 922

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

Upvotes: 0

Views: 5473

Answers (3)

Maik Lowrey
Maik Lowrey

Reputation: 17556

You can catch the error and check the status code. then you can handle it. Maybe witch switch case or simple if. i do it for 404 . see the cod below:

axios.post("http://localhost:5000/api/featureFlagBadURL", {
    flagName: "newJqueryAjaxListener",
    defaultValue: "false",
  }).then((res) => {
    // handle response => res.data
    console.log(response);
  }).catch((error) => {
    if (error.response) {
      if(error.response.status === 404) {
        console.log('BAD URL')
        // or 
        console.log(error.response.statusText) // "Not Found" 
      }
    }
  }

Upvotes: 1

Tomek Cupiał
Tomek Cupiał

Reputation: 31

Try this way:

  return axios.post("http://localhost:5000/api/featureFlagBadURL", {
    flagName: "newJqueryAjaxListener",
    defaultValue: "false",
  }).then(function (response) {
    // handle success
    console.log(response);
  }).catch(function (error) {
    // handle error
    console.log(error);
  }).then(function () {
    // always executed
  });

source

Upvotes: 0

M0nst3R
M0nst3R

Reputation: 5283

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' };
    }
})

Upvotes: 3

Related Questions