Class-Validator node.js提供自定义的错误信息

问题描述 投票:0回答:1

我有一个自定义的验证器约束和注解,用于检查给定属性的实体是否已经存在,以下是代码。

import { Inject, Injectable } from '@nestjs/common';
import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint } from 'class-validator';
import { ValidatorConstraintInterface } from 'class-validator/types/validation/ValidatorConstraintInterface';
import { Connection } from 'typeorm';
import { InjectConnection } from '@nestjs/typeorm';

@ValidatorConstraint({ async: true })
@Injectable()
export class EntityExistsConstraint implements ValidatorConstraintInterface {

  constructor(@InjectConnection() private dbConnection: Connection) {
  }

  defaultMessage(validationArguments?: ValidationArguments): string {
    return `${validationArguments.constraints[0].name} with ${validationArguments.property} already exists`;
  }

  validate(value: any, validationArguments?: ValidationArguments): Promise<boolean> | boolean {
    const repoName = validationArguments.constraints[0];
    const property = validationArguments.property;
    const repository = this.dbConnection.getRepository(repoName);
    return repository.findOne({ [property]: value }).then(result => {
      return !result;
    });
  }

}

export function EntityExists(repoName, validationOptions?: ValidationOptions) {
  return function(object: any, propertyName: string) {
    registerDecorator({
      target: object.constructor,
      propertyName: propertyName,
      options: validationOptions,
      constraints: [repoName],
      validator: EntityExistsConstraint,
    });
  };
}

一切工作正常,但当验证失败时,我收到了这样的响应

{
    "statusCode": 400,
    "message": [
        "User with email already exists"
    ],
    "error": "Bad Request"
}

我希望错误是Conflict Exception=>statusCode 409,如何实现?

node.js customvalidator custom-error-handling class-validator
1个回答
1
投票

class-validator不对http代码做任何事情。它只是验证并返回一个错误列表或一个空数组。

你需要做的是检查你所使用的框架,我假设是nestjs或者路由控制器。

如果是路由控制器,你需要写自己的中间件,并禁用默认的中间件(它将验证错误转换为400个坏的请求).更多信息在这里。https:/github.comtypestackrouting-controllers#errorhandlers。

在nestjs的情况下--同样的步骤。更多信息你可以在这里找到。https:/docs.nestjs.comexception-filters#catch-everything。

© www.soinside.com 2019 - 2024. All rights reserved.