最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

网站源码admin26浏览0评论

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

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

我正在尝试为微服务创建共享模块。

有两种套餐:

  • @name/hub - 普通 HTTP 服务
  • @name/lib - 共享库

库包含简单的异常过滤器模块:

  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-fitters.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 {}

服务包含使用此过滤器的控制器:

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

@Module({
  imports: [ExceptionsFiltersModule, ...],
})
export class AppModule {}
  1. 控制器.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();

然后我尝试触发这个过滤器,我收到一般响应:

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

如果有人有意见,请告诉我。谢谢

回答如下:

对我来说同样的问题。

这是因为您在共享库上使用的 HttpException 实例与您在主项目上使用的版本不同(即使它具有相同的名称和版本)。

有效地,使用 @Catch() 而不是 @Catch(HttpException) 解决问题,因为它捕获所有异常。

如果您找到任何其他解决方案,请告诉我。

发布评论

评论列表(0)

  1. 暂无评论