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

27 lines
704 B
TypeScript
Raw Normal View History

2024-02-28 08:32:35 +08:00
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
RequestTimeoutException,
} from '@nestjs/common'
import { Observable, TimeoutError, throwError } from 'rxjs'
import { catchError, timeout } from 'rxjs/operators'
@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),
catchError((err) => {
if (err instanceof TimeoutError)
return throwError(new RequestTimeoutException('请求超时'))
return throwError(err)
}),
)
}
}