首页 > 解决方案 > 如何全局捕获 axios 错误并有时能够推翻它们

问题描述

目前我正在使用响应拦截器instance.interceptors.response.use进行全局错误处理。在那个函数中,我在 404 的情况下重定向,我在 401 等情况下清除存储。效果很好:)

除了现在我有一个地方我想以不同的方式处理 404 错误,但是一个简单的 try/catch 或 .catch 将不起作用,因为 axios 拦截器会拦截响应并立即重定向。

在这种情况下,最佳做法是什么?

我的拦截器:

function onResponseRejected(error) {
  const { response } = error;

  if (!response) return Promise.reject(error); // network error, not axios related
  const { status } = response;
  const { errors } = response.data;

  if (status === 403) {
    router.push({ name: '403' });
  } else if (status === 404) {
    router.push({ name: '404' });
  }
....
....

我的 axios 请求

export const fetch = (some) => {
  return get(`some/${someId}/url/`)
}

我的应用程序对请求的使用

const response = fetch(this.$route.params.connectorId, this.$route.params.mapperId).catch(() => {
  console.log('At this moment the request will be redirected to another route...');
});

标签: javascriptvue.jsecmascript-6axios

解决方案


推荐阅读