如何全局或从一点管理 axios 错误 [英] How to manage axios errors globally or from one point
问题描述
我的应用程序中到处都是标准的 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屋!