@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
intercept(ctx: ExecutionContext, next: CallHandler) {
return next.handle().pipe(
timeout(5000),
catchError((err) =>
err instanceof TimeoutError
? throwError(() => new RequestTimeoutException())
: throwError(() => err),
),
);
}
}
Add the RxJS timeout(5000) operator to next.handle(), then turn its error into a 408.
- If no value arrives within 5 seconds,
timeout(5000)fails the stream with aTimeoutError. catchErrorturns thatTimeoutErrorinto Nest'sRequestTimeoutException.- Nest's exception layer turns
RequestTimeoutExceptioninto a 408 response. - Other errors are rethrown unchanged, so the normal filters handle them.
What the timeout stops: only the waiting for the result. It does not cancel the work the handler started. A slow database query or HTTP call keeps running in the background, and its result is thrown away.
To really stop that work, you need cancellation at the source. Examples: an AbortController passed to the HTTP client, or a statement timeout set on the database.
- Add the RxJS
timeout()operator tonext.handle(). catchErrorturnsTimeoutErrorintoRequestTimeoutException.- Other errors are rethrown unchanged.
- The timeout does not cancel the work the handler started.
Read more
- Interceptors (https://docs.nestjs.com/interceptors)docs.nestjs.com