[英]Unable to implement interceptor for cancelling axios request in case of timeout
In my Nestjs app I am using making Axios calls. 在我的Nestjs应用程序中,我正在使用Axios调用。 I am trying to attach token to every axios request and only if there is a timeout error I want it to cancel the token, log error and stop that request. 我正在尝试将令牌附加到每个axios请求,并且只有在存在超时错误时我才希望它取消令牌,记录错误并停止该请求。 Currently with this Code, the interceptor works fine but it executes the if (Axios.isCancel(error)) { } block everytime. 目前使用此代码,拦截器工作正常但每次都执行if(Axios.isCancel(error)){}块。 Even if there is no timeout and I get a valid Response. 即使没有超时,我也会获得有效的响应。 I don't want to cancel token if there is no timeout. 如果没有超时,我不想取消令牌。
Currently for every request I get irrespective of timeout or not!: 目前,无论超时与否,我都会收到任何请求!:
======Request canceled=== Cancel { message: 'Operation canceled due to timeout!' }
import { Injectable, NestInterceptor, CallHandler, HttpCode } from '@nestjs/common';
import { Observable } from 'rxjs';
import Axios from 'axios';
import { request } from 'https';
import { timeout } from 'rxjs/operators';
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(context: any, next: CallHandler): Observable<any> {
const CancelToken = Axios.CancelToken;
const source = CancelToken.source();
const url:string = context.url? context.url: context.args[0].url;
Axios.defaults.timeout = 2000;
Axios.get(url, {
cancelToken: source.token
}).then( (res)=> {
console.log(res,'');
}, error => {
throw new Axios.Cancel('Operation canceled due to timeout!');
}
).catch( (error)=> {
if (Axios.isCancel(error)) {
console.log('=====================Request canceled=======', error);
} else {
// catchError(error => throwError(new Error('Service Timed out!')))
console.log('--else part------------------------------------');
}
});
return next.handle();
}
}
I believe the problem is that you are always throwing a Axios.Cancel
for any error during the request. 我相信问题是你在请求期间总是抛出Axios.Cancel
来处理任何错误。 Maybe you should check it inside the promise error handler, not in the catch block, like this: 也许你应该在promise错误处理程序中检查它,而不是在catch块中,如下所示:
Axios.get(url, {
cancelToken: source.token
}).then( (res)=> {
console.log(res,'');
}, (error) => {
if (Axios.isCancel(error)) {
throw new Axios.Cancel('Operation canceled due to timeout!');
} else {
console.log('IT IS NOT a timout error.');
}
}
).catch( (error)=> {
console.log('Error during token cancelation');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.