代码之家  ›  专栏  ›  技术社区  ›  Qwertie

捕获AXIOS请求错误应用程序范围

  •  1
  • Qwertie  · 技术社区  · 6 年前

    在我的SPA中,我使用AXIOS向API发出请求。我目前使用AXIOS请求拦截器向请求添加auth头,但我也希望使用它们捕获401个错误并删除本地存储的auth令牌。

    我试图将此添加到当前拦截器

       axios.interceptors.response.use((response) => {
            // Set user headers only if they are not blank.
            // If DTA gets a lot of request quickly, it won't return headers for some requests
            // so you need a way to keep headers in localStorage to getting set to undefined
            if (response.headers['access-token']) {
                localStorage.setItem('access-token', response.headers['access-token'])
                localStorage.setItem('client', response.headers.client)
                localStorage.setItem('uid', response.headers.uid)
                localStorage.setItem('token-type', response.headers['token-type'])
            }
    
            if (response.status === 401) {
                localStorage.setItem('access-token', '')
                localStorage.setItem('client', '')
                localStorage.setItem('uid', '')
                localStorage.setItem('token-type', '')
            }
            // You have to return the response here or you won't have access to it
            // later
            return response
        })
    

    但我发现当状态返回错误代码时,截取程序似乎没有运行。是否有任何方法可以在应用程序范围内捕获这些错误,而不必手动将此错误处理添加到每个请求中?

    3 回复  |  直到 6 年前
        1
  •  3
  •   Dinesh Pandiyan    6 年前

    要处理响应中的错误,需要在响应拦截器中使用回调的第二个参数。

    axios.interceptors.response.use((response) => {
      // Set user headers only if they are not blank.
      // If DTA gets a lot of request quickly, it won't return headers for some requests
      // so you need a way to keep headers in localStorage to getting set to undefined
      if (response.headers['access-token']) {
        localStorage.setItem('access-token', response.headers['access-token']);
        localStorage.setItem('client', response.headers.client);
        localStorage.setItem('uid', response.headers.uid);
        localStorage.setItem('token-type', response.headers['token-type']);
      }
    
      // You have to return the response here or you won't have access to it
      // later
      return response;
    }, (error) => {
      // do what you want to do when error happens
      if (error.response.status === 401) {
        localStorage.setItem('access-token', '');
        localStorage.setItem('client', '');
        localStorage.setItem('uid', '');
        localStorage.setItem('token-type', '');
      }
    
      else if(error.response.status === 500) {
        // do something for all 500 errors
      } else {
        // do something for all other error codes
      }
    
      // should reject the promise so your api call goes to catch block
      return Promise.reject(error);
    });
    

    参考 official axios docs 更多信息

    我在NPM中发布了一个AXIOS拦截器库。有关拦截器中错误处理的更多详细信息,可以参考源代码。

    axios-retry-intercceptor

        2
  •  1
  •   Łukasz Blaszyński    6 年前

    向拦截器“ErrorResponseHandler”添加第二个函数:

    function errorResponseHandler(error) {
    
    }
    
    // apply interceptor on response
    axios.interceptors.response.use(
        response => response,
        errorResponseHandler
    );
    
        3
  •  1
  •   dashboard bloodyKnuckles    6 年前

    可以定义和导出接受 error 参数在一个helper、util等类中,然后可以使用每个catch块中的一行来调用此方法。

    或者,

    定义一个 doRequest() 方法,它一起处理进程的发送和响应处理,并向该方法提供与请求相关的自定义参数,如 { url: 'A', method: X, data : Y} ,从任意位置调用此助手方法。