如何全局或从一个角度管理axios错误

hid*_*dar 1 javascript try-catch promise axios vuejs2

我在我的应用程序中都有标准的then / catch axios代码,一个简单的例子就是这样。

axios.get('/').then( r => {} ).catch( e => {} )
Run Code Online (Sandbox Code Playgroud)

上面的问题是我必须复制该catch()块以处理可能在我的应用程序中调用的任何潜在错误,而我的问题是,是否可以采取任何措施从入口点(相对于全局)捕获错误到处使用捕获。

我正在从axios端或vue寻找解决方案,因为我的应用是使用vue构建的

Eme*_*jeh 18

虽然在某些情况下仅在拦截器内部全局处理错误是可行的,但有时您需要更多控制是否应全局处理错误。

我个人在全局范围内编写错误并在本地调用处理程序。通过这种方法,我可以决定在某些情况下不全局处理错误。我也可以决定仅在满足某些条件时调用全局处理程序。

下面是一个全局组合错误处理程序的简单实现。为了更好地理解这种技术,您可能需要查看这篇文章(A short story on ajax error handlers)

import axios from 'axios';
import {notifier} from './util';

// errorComposer will compose a handleGlobally function
const errorComposer = (error) => {
    return () => {
        const statusCode = error.response ? error.response.status : null;
        if (statusCode === 404) {
            notifier.error('The requested resource does not exist or has been deleted')
        }

        if (statusCode === 401) {
            notifier.error('Please login to access this resource')
        }
    }
}

axios.interceptors.response.use(undefined, function (error) {
    error.handleGlobally = errorComposer(error);

    return Promise.reject(error);
})


// Fetch some missing information
axios.get('/api/articles/not-found').then(resp => {
    // Do something with article information
}).catch(error => {
    const statusCode = error.response ? error.response.status : null;
    // We will handle locally
    // When it's a 404 error, else handle globally
     if (statusCode === 404) {
        // Do some specific error handling logic for this request
        // For example: show the user a paywall to upgrade their subscription in order to view achieves
    } else {
        error.handleGlobally && error.handleGlobally();
    }
})

// Fetch some missing information
axios.get('/api/users/not-found').then(resp => {
    // Do something with user information
}).catch(error => {
    // We want to handle globally
    error.handleGlobally && error.handleGlobally();
})
Run Code Online (Sandbox Code Playgroud)

  • 这就是 axios 真正让我烦恼的地方——错误处理 API 绝对是一团糟。我和OP有同样的问题,即使有你的建议我也不满意。它应该允许我做的是能够自动处理某些事情,但仍然允许我覆盖,但它不能。 (4认同)

tha*_*ksd 5

您应该使用拦截器

首先,使用create方法创建axios实例。这就是您需要在整个应用程序中使用的内容,而不是axios直接引用的内容。它看起来像这样:

let api = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});
Run Code Online (Sandbox Code Playgroud)

然后将拦截器附加到您的axios实例上,以在对该实例的每个请求的响应之后进行调用:

api.interceptors.response.use((response) => response, (error) => {
  // whatever you want to do with the error
  throw error;
});
Run Code Online (Sandbox Code Playgroud)