8

让我们在 NestJS 项目中使用这个控制器:

  @Post('resetpassword')
  @HttpCode(200)
  async requestPasswordReset(
    @Body() body: RequestPasswordResetDTO,
  ): Promise<boolean> {
    try {
      return await this.authService.requestPasswordReset(body);
    } catch (e) {
      if (e instanceof EntityNotFoundError) {
        // Throw same exception format as class-validator throwing (ValidationError)
      } else throw e;
    }
  }

Dto定义:

export class RequestPasswordResetDTO {
  @IsNotEmpty()
  @IsEmail()
  public email!: string;
}

我想在抛出异常时抛出ValidationError格式错误(属性、值、约束等)。this.authService.requestPasswordReset(body);EntityNotFoundError

如何手动创建此错误?这些错误只是在 DTO 验证class-validator失败时抛出。这些可以只是静态验证,而不是异步数据库验证。

所以最终的 API 响应格式应该是例如:

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": [
        {
            "target": {
                "email": "not@existing.email"
            },
            "value": "not@existing.email",
            "property": "email",
            "children": [],
            "constraints": {
                "exists": "email address does not exists"
            }
        }
    ]
}

我需要它有一致的错误处理:)

4

3 回答 3

12

添加ValidationPipe到您的应用程序时,提供自定义exceptionFactory

  app.useGlobalPipes(
    new ValidationPipe({
      exceptionFactory: (validationErrors: ValidationError[] = []) => {
        return new BadRequestException(validationErrors);
      },
    })
  );

这应该是获得预期结果所需的全部内容。

为了比较,您可以在此处查看原始 NestJS 版本。

于 2020-04-30T14:16:26.210 回答
2

您可以使用异常过滤器来创建对该异常的自定义响应首先我们定义异常过滤器:

import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';
// import { EntityNotFoundError } from 'wherever';

@Catch(EntityNotFoundError)
export class EntityNotFoundExceptionFilter 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": 400,
        "error": "Bad Request",
        "message": [
          {
            "target": {},
            "property": "email",
            "children": [],
            "constraints": {
              "isEmail": "email must be an email"
            }
          },
          // other field exceptions
        ]
      });
  }
}

然后回到你的控制器,你使用过滤器:

  // ...
  import { EntityNotFoundExceptionFilter } from 'its module';
  // ...
  @Post('resetpassword')
  @HttpCode(200)
  @UseFilters(EntityNotFoundExceptionFilter)
  async requestPasswordReset(
    @Body() body: RequestPasswordResetDTO
  ): Promise<boolean> {
      return await this.authService.requestPasswordReset(body);
  }

这应该工作得很好。

于 2020-02-18T03:46:08.007 回答
0

我们可以取回由抛出的异常响应class-validator并设置为响应,

import {
  ArgumentsHost,
  BadRequestException,
  Catch,
  ExceptionFilter
} from '@nestjs/common';

@Catch()
export class ValidationFilter < T > implements ExceptionFilter {
  catch (exception: T, host: ArgumentsHost) {
    if (exception instanceof BadRequestException) {
      const response = host.switchToHttp().getResponse();
      response.status(exception.getStatus())
        .json(exception.getResponse());
    }
  }
}

控制器应该看,

@Post('create')
@UsePipes(ValidationPipe)
@UseFilters(ValidationFilter)
async create(@Body() body: CreateDto) {

}

于 2022-02-25T13:17:31.167 回答