简体   繁体   English

Axios拦截器的错误处理程序何时被调用?

[英]When does an Axios interceptor's error handler get called?

I have setup an axios interceptor with the aim of putting a global loading variable to true when any request has not received a response. 我已经设置了axios拦截器,目的是在任何请求都未收到响应时将全局加载变量设置为true。 In my app this will prevent the user from submitting a form which is many cases could cause errors as all data has not yet been processed. 在我的应用程序中,这将阻止用户提交表单,这在很多情况下可能会导致错误,因为尚未处理所有数据。

The code is: 代码是:

var numberOfAjaxCAllPending = 0;
// Add a request interceptor
window.axios.interceptors.request.use(function (config) {
    numberOfAjaxCAllPending++;
    console.log('Request:  ---- ' + numberOfAjaxCAllPending);
    return config;
}, function (error) {
    return Promise.reject(error);
});

// Add a response interceptor
window.axios.interceptors.response.use(function (response) {
    numberOfAjaxCAllPending--;
    console.log('Pending Response (response): ---- ' + numberOfAjaxCAllPending);
    return response;
}, function (error) {
    numberOfAjaxCAllPending--;
    console.log('Pending Response (error): ---- ' + numberOfAjaxCAllPending);
    return Promise.reject(error);
});

global.loading = numberOfAjaxCAllPending > 0;

As a request is made, the pending counter is incremented and as a response comes back in its decremented. 发出请求后,待处理的计数器将递增,而响应以递减的形式返回。 A value greater than 0 means requests are still pending. 大于0的值表示请求仍在等待处理中。

I am a little confused about the error part of the promise on each of these. 我对每个承诺的错误部分感到困惑。 I have to add the decrement pending to response error so that it can catch non 200 responses. 我必须将减量挂起添加到响应错误,以便它可以捕获非200个响应。

With the request, I assume if there is an error then the request will not send and I will not be expecting a response. 对于该请求,我假设如果有错误,则该请求将不会发送,并且不会收到响应。 Is this correct? 这个对吗?

On request interceptor, you also need to decrement the value if you dont want to wait for response. 在请求拦截器上,如果您不想等待响应,则还需要减小该值。

Function in request interceptor will be invoked before it does request. 请求拦截器中的函数将在请求之前被调用。

Function in response interceptor will be invoked after response is received. 收到响应后,将调用响应拦截器中的函数。

That said if error occurs after request interceptor is called, you need to decrement the value. 也就是说,如果在调用请求拦截器后发生错误,则需要减少该值。 If error occurs before request interceptor, you dont need to decrement it. 如果在请求拦截器之前发生错误,则无需减少它。

It just depends on when the error occurs. 它仅取决于错误发生的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM