简体   繁体   中英

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

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

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

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" 
      }
    }
  }

Try using async await by enclosing your code in a function if it has huge data.

Or try changing the port from 5000 to 4000 or 3000. See if this works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM