Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios.catch does not catch network/console errors [duplicate]

I am using React with axios and redux-promise. Axios does not appear to catch the 404 error, as below.

axios writes the 404 error to the console, even when I am handling it

This is the code.

 const url = FIVE_DAY_FORECAST_URL.replace("{0}", city);

  axios.interceptors.response.use(function (response) {
    return response;
  }, function (error) {
     return Promise.reject(error);
  });

  try{
    const request = axios.get(`${url}`).then(e => { 
       debugger; }).catch(
      e => {
        debugger;
        return "ERROR"; // THIS FIRES, BUT DOES NOT STOP THE CONSOLE ERROR
      });
      debugger;
    return {
      type: FETCH_FIVE_DAY_FORECAST,
      payload: request
    };
  } catch {
    debugger;
    console.log("Error!");  // DOES NOT HELP AS THE 404 IS NOT A JAVASCRIPT ERROR, IT'S A VALID SERVER RESPONSE
  }
}

I am using a number of techniques to tr to catch the console error:

  • .then() ==> the code runs through this block, but the error has already happened, and has been written to the console!

  • .catch() ==> the code runs through this block if the interceptors are not configured i.e. comment out axios.interceptors.response.use... .

  • try...catch ==> no effect (does not catch the network response as this is not really a javascript error!)

like image 531
Banoona Avatar asked Oct 16 '22 05:10

Banoona


1 Answers

When using try...catch with axios you explicitly have to state the error response like so

catch(error) {
  console.log('[error]', error.response);
  // use the error.response object for some logic here if you'd like
}

Otherwise it just returns the string value.

With that response object you can then utilize some logic to do something based on the particular error. More info can be found here https://github.com/axios/axios/issues/960

I hope this helps.

like image 114
Mark Avatar answered Oct 23 '22 03:10

Mark