【问题标题】:What is the correct way to create exception with NestJS and class-validator?使用 NestJS 和类验证器创建异常的正确方法是什么?
【发布时间】:2021-07-26 23:10:34
【问题描述】:

我正在使用class-validatorNestJS,我面临以下情况:基本上我已经定义了一个具有以下结构的Dto 文件:

import {
  IsNotEmpty,
  IsEmail,
  IsDate,
  MaxDate,
  MinLength,
  MaxLength,
  Matches,
  IsString,
} from 'class-validator'
import { Type } from 'class-transformer'

export class CreateUserDto {
  @MinLength(5)
  @MaxLength(10)
  username: string

  @IsNotEmpty()
  @IsEmail()
  email: string

  @IsString()
  @MinLength(4)
  @MaxLength(20)
  @Matches(/((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$/, {
    message: 'password too weak',
  })
  password: string

  @IsNotEmpty()
  @IsDate()
  @Type(() => Date)
  @MaxDate(require('moment')().subtract(13, 'y').toDate())
  dateOfBirth: Date

  @IsNotEmpty()
  firstName: string

  @IsNotEmpty()
  lastName: string
}

所以当我调用auth/register 时,class-validator 会自动检查POST 并验证所有字段,并在出现异常时返回:

{
    error: 'Bad Request',
    message: ['password too weak']
    statusCode: 400
}

这很好,但如果我使用 NestJS 生成自定义异常:

let exists = await this.userService.findByEmail(createUserDto.email)
if (exists) throw new ConflictException('email already exists')

我明白了:

{
    error: 'Bad Request',
    message: 'email already exists'
    statusCode: 400
}

如您所见,message 不是数组,而且这种缺乏一致性。要解决这种情况,我必须用['email already exists'] 包围消息。

这是一个好方法还是我把事情复杂化了?

【问题讨论】:

    标签: nestjs class-validator


    【解决方案1】:

    如果有任何错误,Class-valditor 会返回一个错误数组,这就是您在消息中得到这种差异的原因。您可以创建一个过滤器来将错误数组更改为换行符分隔的字符串或类似字符串,或者您可以将它们保持原样,或者您可以将字符串数组传递给错误构造函数。都是有效的好方法

    【讨论】:

    • 你能告诉我如何创建一个全局过滤器,它还自动在数组中添加未处理的异常,如 500?谢谢
    • @sfarzoso 关注此docs.nestjs.com/exception-filters#exception-filters-1。由于类验证器会抛出一个 BadRequest 异常,因此您可以简单地将其传递到 @Catch(BadRequestException) 中并捕获它,然后按照您想要的方式发送响应。
    猜你喜欢
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 2015-09-06
    • 1970-01-01
    • 2021-11-24
    • 2016-02-07
    相关资源
    最近更新 更多