简体   繁体   中英

Binding interceptor to NestJS microservice method

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);
}

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM