繁体   English   中英

如何在 Nestjs 中使用 globalPipse 进行自定义响应

[英]How to make custom response using globalPipse in nestjs

我使用'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
}

我可以获得维护上述代码的自定义响应吗?
如果它可以做到,你能给我一些建议或一些代码吗?
感谢您阅读我的问题。

在 Nest 中,管道非常适合验证、转换传入的 object、在某些情况下可能与数据库通信,并在出现任何问题时抛出错误。 如果要更改响应,则在引发错误后,您需要考虑使用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
      });
  }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM