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

编程入门 行业动态 更新时间:2024-10-05 13:25:00

How to use external (from another package) <a href=https://www.elefans.com/category/jswz/34/1767566.html style=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) 解决问题,因为它捕获所有异常。

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

更多推荐

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

本文发布于:2024-05-30 22:44:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1771005.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:exception   package   external   js   Nest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!