score:0

You are trying to catch the Promise.reject and wrapping it in a try...catch. Only one of this will work.

You can either catch a promise rejection or wrap the promise in a try...catch and throw a new error on promise rejection and catch it in catch block.

Try this 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(
    response => {
      debugger;
    })
    .catch(
    e => {
      debugger;
      throw e // throw the error and catch it
    });
    debugger;
  return {
    type: FETCH_FIVE_DAY_FORECAST,
    payload: request
  };
} catch {
  debugger;
  // Now you can catch the error in catch block
  console.log("Error!");
}

// or you can't write async/await code
// make the the function is marked as `async`

try {
  const response = await axios.get(`${url}`)
  return {
    type: FETCH_FIVE_DAY_FORECAST,
    payload: response
  };
} catch (e) {
  console.error("Error happened during fetch");
  console.error(e);
}

score:3

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.


Related Query

More Query from same tag