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

新手上路,请多包涵

我的应用程序中到处都是标准的 then/catch axios 代码,一个简单的代码就是这样……

 axios.get('/').then( r => {} ).catch( e => {} )

我在上面遇到的问题是我必须复制 catch() 块来处理我在我的应用程序中调用的任何潜在错误,我的问题是,如果有什么我可以做的来捕捉错误全局从入口点开始,而不是在任何地方使用 catch。

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

原文由 hidar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 334
2 个回答

你应该使用 拦截器

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

 let api = axios.create({
  baseURL: 'https://example.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

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

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

原文由 thanksd 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

下面是一个全局组合的错误处理程序的简单实现。为了更好地理解这项技术,您可能需要查看这篇 文章(关于 ajax 错误处理程序的短篇小说)

 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();
})

原文由 Emeke Ajeh 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题