CodePark/ questions / Interceptors
START PRACTICINGPRACTICE
Backend question · NestJS › Interceptors

Write an interceptor that fails a request with 408 if the handler takes longer than 5 seconds. What does the timeout actually stop?

@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 a TimeoutError.
  • catchError turns that TimeoutError into Nest's RequestTimeoutException.
  • Nest's exception layer turns RequestTimeoutException into 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 to next.handle().
  • catchError turns TimeoutError into RequestTimeoutException.
  • Other errors are rethrown unchanged.
  • The timeout does not cancel the work the handler started.