【问题标题】:How to make custom response using globalPipse in nestjs如何在 Nestjs 中使用 globalPipse 进行自定义响应
【发布时间】:2021-04-08 22:40:16
【问题描述】:

我使用 'class-validator' 的 dto 在 user.controller 中编写了一个 api。

  @Post('/')
  public async createUser(
    @Res() res,
    @Body() createUserDto: CreateUserDto,
  ) {
    ... do something
  }

我将 useGlobalPipes 放在 main.ts 中。

  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      transform: true,
      forbidNonWhitelisted: true,
      transformOptions: {
        enableImplicitConversion: true,
      },
    }),
  );

当我向 api 请求时,我会在下面得到响应。

{
    "statusCode": 400,
    "message": [
        "userName should not be empty",
        "userName must be a string",
    ],
    "error": "Bad Request"
}

到目前为止,它与 nestjs 一起工作没有问题。
但我想得到这样的自定义响应。

{
    "code": 400,
    "errorReason": [
        "userName should not be empty",
        "userName must be a string",
    ],
    "msg": "Bad Request",
    "success": false
}

我能否在维护上述代码的情况下获得此自定义响应?
如果可以的话,你能给我一些建议或一些代码吗?
感谢您阅读我的问题。

【问题讨论】:

    标签: javascript node.js typescript nestjs


    【解决方案1】:

    在 Nest 中,管道适用于验证、转换传入对象、可能在某些情况下与数据库通信,以及在出现任何问题时抛出错误。如果您想更改响应,则在引发错误后,您需要考虑使用 ExceptionFilter 在哪里可以执行类似的操作

    @Catch()
    export class CatchAllFilter implements ExceptionFilter {
    
      catch(exception: Error, host: ArgumentHost) {
        res
          .status((exception.getStatus && exception.getStatus()) || 500)
          .send({
            (exception.getResponse && ...exception.getResponse()) || ...{ message: exception.message },
            success: false
          });
      }
    }
    

    上面的代码肯定会出现类型错误,但它应该会引导你走上正确的轨道

    【讨论】:

      猜你喜欢
      • 2021-04-09
      • 2022-11-21
      • 1970-01-01
      • 2022-08-07
      • 2022-07-07
      • 2022-07-02
      • 2020-03-14
      • 2020-01-09
      • 2019-07-09
      相关资源
      最近更新 更多