如何全局或从一个角度管理axios错误 [英] How to manage axios errors globally or from one point

查看:39
本文介绍了如何全局或从一个角度管理axios错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the standard then/catch axios code all over my app, a simple one goes likes this..

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

上述问题是我必须复制 catch()块来处理在应用程序中调用的任何潜在错误,而我的问题是,是否有任何错误可以从入口点全局捕获错误,而不是在各处使用catch.

The problem I have with the above is that I have to duplicate the catch() block to handle any potential errors that my be invoked in my app and my questions is, if there is anything I can do to catch the errors globally from on entry point as opposed to using catch everywhere.

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

I am looking for solutions from either axios side or vue, since my app is built with vue

推荐答案

您应该使用拦截器.

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

First, create an axios instance using the create method. This is what you would need to use throughout your app instead of referencing axios directly. It would look something like this:

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

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

Then attach an interceptor to your axios instance to be called after the response to each of the requests for that instance:

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

这篇关于如何全局或从一个角度管理axios错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆