Axios.catch无法捕获网络/控制台错误

时间:2019-03-16 04:31:09

标签: javascript reactjs axios

我正在使用带有axios 和redux-promise 的React。如下所示,Axios似乎未捕获到404错误。

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

这是代码。

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

我正在使用多种技术来捕获控制台错误:

  • .then()==>该代码贯穿此块,但错误已经发生,并已写入控制台!

  • .catch()==>如果未配置拦截器,即注释掉axios.interceptors.response.use...,则代码将贯穿此块。

  • try ... catch ==>无效(不会捕获网络响应,因为这实际上不是JavaScript错误!)

2 个答案:

答案 0 :(得分:0)

try...catchaxios一起使用时,您必须像这样明确声明错误响应

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

否则,它仅返回字符串值。

使用该响应对象,您可以根据特定错误利用某种逻辑来执行某些操作。更多信息,请点击此处https://github.com/axios/axios/issues/960

我希望这会有所帮助。

答案 1 :(得分:0)

您正在尝试捕获Promise.reject并将其包装在try...catch中。其中只有一个会起作用。

您可以捕获承诺拒绝,也可以将承诺包装在try...catch中,并在承诺拒绝中引发新的错误,然后将其捕获在catch块中。

尝试此代码

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);
}
相关问题