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

Class-Validator node.js provide custom error

我创建了一个自定义验证器约束和注释,用于检查给定 属性 的实体是否已经存在,这是代码

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,我该如何实现?

class-validator 不对 http 代码做任何事情。它仅验证 returns 错误列表或空数组。

你需要做的是检查你使用的框架,我假设它是 nestjs 或 routing-controllers。

在路由控制器的情况下,您需要编写自己的后中间件并禁用默认中间件(它将验证错误转换为 400 个错误请求)。 更多信息在这里:https://github.com/typestack/routing-controllers#error-handlers

对于 nestjs - 相同的步骤。 您可以在此处找到更多信息:https://docs.nestjs.com/exception-filters#catch-everything