Home > Mobile >  Binding interceptor to NestJS microservice method
Binding interceptor to NestJS microservice method

Time:06-21

I just created a simple interceptor to override every error thrown by my application, just like the one on Nest's documentation:


@Injectable()
export class ErrorsInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next
      .handle()
      .pipe(
        catchError(err => throwError(() => new ApplicationException())),
      );
  }
}

And altough exceptions caused by http requests indeed are caught in that interceptor, I just can't make it work with RPC requests (like KafjaJS and events). Just like the documentation, I've binded it on my app.module:

    {
      provide: APP_INTERCEPTOR,
      useClass: ErrorsInterceptor,
    }

I know I'm probably missing something out, can someone clarify where and why what I'm doing is not working and how to make it work?

@Edit: I forgot to mention that I made it work @UseInterceptors() above my controller's method, but I'd like to make it work without it.

@Edit 2: I have a hybrid appplication, this is what my main looks like (as asked by Jay):

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: WinstonModule.createLogger(winstonTransports),
  });

  app.connectMicroservice<MicroserviceOptions>(kafkaConfig);

  const logger = app.get<winston.Logger>(WINSTON_MODULE_NEST_PROVIDER);
  app.useLogger(logger);
  app.enableCors(corsConfig);

  await app.startAllMicroservices();
  await app.listen(env.PORT);
}

CodePudding user response:

When working with hybrid applications you need to add { inheritAppConfig: true } to the connectMicroservice() method as a second parameter as described in the docs. This means your main.ts should be

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule, {
    logger: WinstonModule.createLogger(winstonTransports),
  });

  app.connectMicroservice<MicroserviceOptions>(kafkaConfig, { inheritAppConfig: true });

  const logger = app.get<winston.Logger>(WINSTON_MODULE_NEST_PROVIDER);
  app.useLogger(logger);
  app.enableCors(corsConfig);

  await app.startAllMicroservices();
  await app.listen(env.PORT);
}
  • Related