URCloud

/ 0评 / 6/ 最后更新:2021-12-06
nestjs 自定义ValidationPipe

需求场景

nestjs内置的ValidationPipe验证管道的返回响应如下

{
  "statusCode": 400,
  "error": "Bad Request",
  "message": [
    {
      "target": {},
      "property": "email",
      "children": [],
      "constraints": {
        "isEmail": "email must be an email"
      }
    }
  ]
}

而实际生产项目中,参数验证往往返回200状态码,我们可能需要形如

{
  success:0,
  message:'',
  data:[]
}

的响应返回。这个时候就需要自定义验证管道。

修改main.ts

通过查看validationPipe源码可以发现(nestjs v7文档中已有,v6文档中没有,似乎也不支持),ValidationPipe有个参数exceptionFactory就是用来自定义返回错误的。修改的具体源码如下

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe, HttpStatus, HttpException } from '@nestjs/common';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(
    new ValidationPipe({
      exceptionFactory: (validationErrors = []) => {
        throw new HttpException(
          {
            success: 0,
            message: Object.values(validationErrors[0].constraints)[0],
          },
          HttpStatus.OK,
        );
      },
    }),
  );
  await app.listen(6000);
}
bootstrap();
6

Leave a Reply

Your email address will not be published.