oa_based/src/common/interceptors/timeout.interceptor.ts

26 lines
697 B
TypeScript
Raw Normal View History

2024-02-28 08:32:35 +08:00
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
RequestTimeoutException,
2024-02-28 17:02:46 +08:00
} from '@nestjs/common';
import { Observable, TimeoutError, throwError } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';
2024-02-28 08:32:35 +08:00
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
constructor(private readonly time: number = 10000) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
return next.handle().pipe(
timeout(this.time),
2024-02-28 17:02:46 +08:00
catchError(err => {
if (err instanceof TimeoutError) return throwError(new RequestTimeoutException('请求超时'));
2024-02-28 08:32:35 +08:00
2024-02-28 17:02:46 +08:00
return throwError(err);
})
);
2024-02-28 08:32:35 +08:00
}
}