You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在NestJS自定义验证器中根据错误自定义提示信息?

在NestJS中自定义CSS验证器并返回具体错误信息

要把PostCSS抛出的具体CSS语法错误返回给UI,你可以通过在验证器实例中存储错误详情,再在defaultMessage方法里动态生成提示内容,具体实现步骤如下:

  • 给CssValidator类添加私有属性,用于临时存储捕获到的错误原因
  • 在validate方法的catch块中,将CssSyntaxError的reason赋值给这个私有属性
  • 在defaultMessage方法中,根据私有属性的值返回对应的提示文本

修改后的完整代码:

import { IsOptional, IsString, Validate } from 'class-validator';
import { ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';
import { Injectable } from '@nestjs/common';
import postcss from 'postcss';

@ValidatorConstraint({ async: true })
@Injectable()
export class CssValidator implements ValidatorConstraintInterface {
  // 存储错误详情的私有属性
  private errorReason?: string;

  async validate(value: string) {
    // 每次验证前重置错误信息,避免残留上一次的验证结果
    this.errorReason = undefined;
    try {
      await postcss.parse(value);
      return true;
    } catch (error) {
      if (error.name === 'CssSyntaxError') {
        this.errorReason = error.reason;
      }
    }
    return false;
  }

  defaultMessage() {
    // 有具体错误原因时返回带详情的提示,否则返回默认提示
    return this.errorReason ? `Invalid CSS: ${this.errorReason}` : 'Invalid CSS provided';
  }
}

export class CustomStylesCreateDto {
  @IsOptional()
  @IsString()
  @Validate(CssValidator)
  styles?: string;
}

注意事项:

  • 每次调用validate时重置errorReason,防止多次验证时错误信息残留
  • 因为验证器标记了async: true,class-validator会确保每个验证请求使用独立的实例,不用担心并发冲突问题

内容的提问来源于stack exchange,提问作者Johnson Cherian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 06:52:09