Axios 请求是 Promise,这意味着它们有一个 then() 函数 用于 承诺链 ,以及 catch() 处理错误的函数。 以下是您可以如何 catch()Axios 中的错误。
const err = await axios.get(https://httpbin.org/status/404).
  catch(err => err);
err instanceof Error; // true
err.message; // Request failed with status code 404catch() 完全相同于 Promise 的 catch() 功能 。 所以你可以使用承诺链,并添加一个 catch() 最后处理承诺链中发生的任何错误。
const err = await axios.get(https://httpbin.org/status/200).
  // Will throw a TypeError because the property doesnt exist.
  then(res => res.doesNotExist.throwAnError).
  catch(err => err);
err instanceof TypeError; // true你也可以使用 catch() 要转换错误,只需确保之后重新抛出错误。
let error;
try {
  await axios.get(https://httpbin.org/status/404).catch(err => {
    if (err.response.status === 404) {
      throw new Error(`${err.config.url} not found`);
    }
    throw err;
  });
} catch (err) {
  error = err;
}
error.message; // https://httpbin.org/status/404 not found您还可以 使用拦截器自动使 Axios 转换错误 。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
    









请登录后查看评论内容