'How to use external (from another package) exception filter Nest.js?

I'm trying to create shared-module for microservices.

There are two packages:

  • @name/hub - ordinary HTTP-service
  • @name/lib - shared library

Library contains simple exception-filter module:

  1. http.exception-filter.ts
import { ArgumentsHost, Catch, ExceptionFilter, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: exception.message,
    });
  }
}
  1. exceptions-fitlers.module.ts
import { Module, Scope } from '@nestjs/common';
import { HttpExceptionFilter } from './http.exception-filter';
import { APP_FILTER } from '@nestjs/core';

@Module({
  providers: [
    {
      provide: APP_FILTER,
      scope: Scope.REQUEST,
      useClass: HttpExceptionFilter,
    },
  ],
})
export class ExceptionsFiltersModule {}

Service contains controller that uses this filter:

  1. app.module.ts
import { Module } from '@nestjs/common';
import { ExceptionsFiltersModule } from '@name/nodejs-lib/dist';

@Module({
  imports: [ExceptionsFiltersModule, ...],
})
export class AppModule {}
  1. controller.ts
@Controller('app')
@UseFilters(new HttpExceptionFilter())
export class AppController{
  @Post('/check')
  @HttpCode(200)
  async check(@Body() dto: A): Promise<B> {
    throw new BadRequestException('Invalid data');
  }
}
  1. main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './modules/app.module';
import { ConfigService } from '@nestjs/config';
import { DocumentationBuilder, HttpExceptionFilter } from '@name/nodejs-lib/dist';

async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  const config = app.get(ConfigService);

  app.useGlobalFilters(new HttpExceptionFilter());

  await app.listen(config.get<number>('HTTP_PORT'), () => {
    logger.log(`HTTP Server: http://${config.get('HTTP_HOST')}:${config.get('HTTP_PORT')}`);
  });
}

bootstrap().then();

Then I trying trigger this filter, I receive generic response:

{
  "statusCode": 400,
  "message": "Invalid data",
  "error": "Bad Request"
}

If someone has opinion, please let me know. Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source