【问题标题】:Class-Validator node.js provide custom errorClass-Validator node.js 提供自定义错误
【发布时间】:2020-08-02 10:54:30
【问题描述】:

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

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】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多