不向 API 网关抛出 NotFoundException - NESTJS

问题描述 投票:0回答:1

我有麻烦....我希望API网关捕获NotFoundException,但是,每次我重新创建时,即使在chatgpt或claude的帮助下,API网关也没有捕获NotFoundException.....(抱歉,我一直在学习nestjs)

API网关的错误:

{“context”:“ExceptionsHandler”,“level”:“error”,“message”:“内部服务器错误”,“stack”:[null],“timestamp”:“2024-09-22T17:56:02.987 Z”}

但是,在服务中,出现了 NotFoundException:

{"level":"error","message":"Error NotFoundException, {"response":{"message":"用户 tidak ditemukan","error":"Not Found","statusCode":404}, "status":404,"options":{},"message":"用户tidak ditemukan","name":"NotFoundException"}","timestamp":"2024-09-22T17:56:02.986Z"}

{"context":"RpcExceptionsHandler","level":"error","message":"用户 tidak ditemukan","stack":["NotFoundException: 用户 tidak ditemukan 在 PekawaiController.getPegawaiByNIP (/app/src/pekawai.controller.ts:46:15) 在异步/app/node_modules/@nestjs/microservices/context/rpc-proxy.js:11:32 在异步 ServerTCP.handleMessage (/app/node_modules/@nestjs/microservices/server/server-tcp.js:67:54)"],"timestamp":"2024-09-22T17:56:02.986Z"}

这是我的 API 网关控制器

 @Get(':NIP')
 getPegawai(@Param('NIP') NIP: string) {
 try {
    const pegawai = this.UserService.send({ cmd: `getPegawaiByNIP` }, NIP);
    this.logger.info(`Data: ${JSON.stringify(pegawai)}`);
    return pegawai;
 catch (error) {
    this.logger.error(`mengambil error ${JSON.stringify(error)}`);
    return error;
    }

这是我的服务控制器

@MessagePattern({ cmd: 'getPegawaiByNIP' })
@Get()
 async getPegawaiByNIP(NIP: string) {
 try {
    const pegawai = await this.appService.getPegawaiByNIP(NIP);
    return pegawai;
 catch (error) {
    this.logger.error(`Error di controller, ${JSON.stringify(error)}`);
    if (error instanceof NotFoundException) {
        this.logger.error(`Error NotFoundException, ${JSON.stringify(error)}`);
        throw new NotFoundException(`User tidak ditemukan`);
    }
    throw new RpcException({
    statuscode: HttpStatus.INTERNAL_SERVER_ERROR,
    message: `Internal Server Error`,
       });
     }
   }

这是我的服务数据库

async getPegawaiByNIP(NIP: string) {
    const pegawai = await this.prisma.pegawai.findFirst({
      where: {
        NIP: NIP,
      },
    }); // Pastikan nama field sesuai dengan schema
    this.logger.info('Data: ' + JSON.stringify(pegawai));

    if (!pegawai) {
      throw new NotFoundException(`User tidak ditemukan`);
    }

    return pegawai;
typescript nestjs httpexception
1个回答
0
投票

看起来问题是由于不同层(控制器、服务、数据库)中的多个

try-catch
块造成的,它捕获了服务或数据库层中的
NotFoundException
并将其转换为另一个错误,例如
RpcException
。这会阻止 API 网关捕获原始数据
NotFoundException

要解决此问题:

  1. 删除控制器和服务层中的
    try-catch
    ——让 NestJS 自动处理异常。
  2. 仅在 DB 层抛出
    NotFoundException
    ,而不将其转换为另一个异常。

这样,API Gateway 将正确捕获并处理

NotFoundException

© www.soinside.com 2019 - 2024. All rights reserved.