简体   繁体   English

如何为 NestJS 上的嵌套验证错误返回干净的消息

[英]How to return a clean message for nested validation error on NestJS

I have a nested form validation on my nestjs application, that returns the following result when a field has some error:我在我的 nestjs 应用程序上有一个嵌套表单验证,当字段出现错误时返回以下结果:

Current error message: "products.0.amount A quantidade do produto é obrigatória"当前错误消息: "products.0.amount A quantidade do produto é obrigatória"

Expected error message: "A quantidade do produto é obrigatória"预期的错误消息: "A quantidade do produto é obrigatória"

For those examples above, I have a form with an attribute called product that is an array of objects对于上面的那些例子,我有一个名为product属性的表单,它是一个对象数组

The issue is that I don't want to return the property name appended to the message, I want to return a clean message, readable for end users问题是我不想返回附加到消息的属性名称,我想返回一个干净的消息,最终用户可以阅读

export class CheckoutForm {
  @ValidateNested({ always: true })
  @Type(() => ProductForm)
  products: ProductForm[];
}
export class ProductForm {
  @IsString({ always: true, message: 'O nome do produto é obrigatório' })
  name: string;

  @Min(1, { always: true, message: 'O preço do produto é obrigatório' })
  value: number;

  @IsNotEmpty({
    always: true,
    message: 'A quantidade do produto é obrigatória',
  })
  amount: number;
}

Looks like this is an open issue with class-validator.看起来这是类验证器的一个未解决问题。 https://github.com/typestack/class-validator/issues/614#issuecomment-807255434 https://github.com/typestack/class-validator/issues/614#issuecomment-807255434

Seems to be nested validation issues if more than one level, which would explain the issues that you are having.如果不止一个级别,似乎是嵌套验证问题,这将解释您遇到的问题。

Since 5.5.0 nestjs have a method to modify the errors on class-validator and class-transformer.从 5.5.0 开始,nestjs 有一种方法可以修改 class-validator 和 class-transformer 上的错误。

in your main.ts you should have在你的 main.ts 你应该有

  await app.useGlobalPipes(new ValidationPipe());

this method receives a parameter named "exceptionFactory", which receives a function that can return an exception.该方法接收一个名为“exceptionFactory”的参数,该参数接收一个可以返回异常的function。 if you want to modify and specific error you can do something like this如果你想修改特定的错误,你可以做这样的事情

   await app.useGlobalPipes(new ValidationPipe({
    exceptionFactory: (errors: ValidationError[]) =>
    {
      const customError = errors.map((el) =>
      {
        if(el.constraints.isString)
        {
          return "O nome do produto é obrigatório"
        }

        if(el.constraints.isNotEmpty)
        {
          return "A quantidade do produto é obrigatória"
        }

      });
      
      return new HttpException(customError, HttpStatus.BAD_REQUEST);
    }
  }));

notices I have an array of errors this is because I use graphql maybe in your case in REST is different however if you console.log this errors you get an array whit this values通知我有一系列错误,这是因为我使用 graphql 可能在你的情况下 REST 是不同的,但是如果你 console.log 这个错误你会得到一个包含这个值的数组

[
  ValidationError {
    target: SignUpInput {
      confirmPassword: '123',
      email: 'text@gmail.com',
      name: '',
      password: '123',
      surname: ' '
    },
    value: '',
    property: 'name',
    children: [],
    constraints: {
      minLength: 'name must be longer than or equal to 3 characters',
      isAlpha: 'name must contain only letters (a-zA-Z)'
    }
  }
]

in the constraints elements are the errors of the validations do you have whit this you can modify the errors.在约束元素中是验证的错误你有这个你可以修改错误。

IMPORTANT: "exceptionFactory" should return a valid exeption otherwise it wont work重要提示:“exceptionFactory”应该返回一个有效的例外,否则它不会工作

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

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