Home > Enterprise >  NestJS handle timeout
NestJS handle timeout

Time:10-28

I have heavy request which takes more than 5 minutes to execute. In my logs I see that NestJS throws every 5 min new request by itself, but I don't see request from browser. As it was recommended I set

const app = await app.listen();
app.setTimeout(1800000);

and in my rout

    @Get('/foo')
    async foo(@Req() req) {
      req.setTimeout(1800000);
      //...
    }

but it doesn't work, I see every 5 minutes new request in my logs. I know, the best solution is making a queue and handle it asynchronously but for this moment I need just increase timeout somehow. Is it possible?

CodePudding user response:

You should use nginx or apache for that.

   proxy_read_timeout 5;
   proxy_connect_timeout 5;
   proxy_send_timeout 5;

But if you want to set it on express - try this: http://expressjs.com/en/resources/middleware/timeout.html

CodePudding user response:

Did you try this ?

Example:

import { Injectable, NestInterceptor, ExecutionContext, CallHandler, RequestTimeoutException } from '@nestjs/common';
import { Observable, throwError, TimeoutError } from 'rxjs';
import { catchError, timeout } from 'rxjs/operators';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      timeout(5000),
      catchError(err => {
        if (err instanceof TimeoutError) {
          return throwError(() => new RequestTimeoutException());
        }
        return throwError(() => err);
      }),
    );
  };
};
  • Related