如何在 ValidationPipe 校验失败时返回对应语言的错误提示?

解读

国内项目普遍要求“中英双语”或“多语言”提示,面试官问这一题,核心想确认三件事:

  1. 你是否知道 ValidationPipe 只是把 class-validator 的错误对象转给 ExceptionFilter,真正的“文案”在 class-validator 的 decorator 里;
  2. 你是否能把“语言”这个运行时变量(取自 header、query、用户表字段等)注入到校验流程;
  3. 你是否了解 NestJS 的依赖注入与拦截器/过滤器链,能把国际化(i18n)做成“全局统一、业务无侵入、可单元测试”的企业级方案。

只答“用 i18n 包”是不够的,必须给出可落地的代码路径与异常处理闭环。

知识点

  • ValidationPipe 构造参数:exceptionFactory、transform、transformOptions、validatorOptions
  • class-validator 的 ValidationError 结构:constraints、property、target、children
  • class-validator 支持动态 message 函数:@IsNotEmpty({ message: (args) => … })
  • NestJS 官方 nestjs-i18n 或自研 I18nService,作用域:Request 作用域
  • REQUEST 作用域提供者注入方式:scope: Scope.REQUEST、@Inject(REQUEST)
  • ExceptionFilter 捕获 BadRequestException,统一格式化 code、msg、data
  • Accept-Language、X-Lang、user.language 三种语言来源优先级
  • 性能:ValidationPipe 高频调用,应避免每次 new,使用全局单例 + 请求级语言变量
  • 单元测试:mock I18nService、mock REQUEST,验证中英文提示是否正确

答案

步骤一:建立语言上下文

  1. 在 main.ts 注册全局 ValidationPipe,并传入请求级语言变量
app.useGlobalPipes(new ValidationPipe({
  transform: true,
  whitelist: true,
  forbidNonWhitelisted: true,
  exceptionFactory: (errors: ValidationError[]) => {
    // 语言标记在请求头 X-Lang 中,通过 IoC 拿到 I18nService
    const i18n = errors[0].target['__i18n__'];   // 见步骤二注入
    const lang = errors[0].target['__lang__'];   // 见步骤二注入
    const messages = errors.map(e => i18n.t(`validation.${e.property}.${Object.keys(e.constraints)[0]}`, lang));
    throw new BadRequestException({
      code: 40001,
      msg: messages.join('; '),
      data: null,
    });
  },
}));

步骤二:把 I18nService 与语言注入到 DTO
2. 利用 nestjs-i18n 的 I18nRequestScopeService(REQUEST 作用域)

@Injectable({ scope: Scope.REQUEST })
export class ValidationI18nHelper {
  constructor(
    @Inject(REQUEST) private req: Request,
    private i18n: I18nRequestScopeService,
  ) {}

  assignMeta<T extends object>(dto: T): T {
    (dto as any).__i18n__ = this.i18n;
    (dto as any).__lang__ = this.req.headers['x-lang'] || 'zh-CN';
    return dto;
  }
}
  1. 在拦截器里统一给 DTO 注入元数据
@Injectable()
export class I18nValidationInterceptor implements NestInterceptor {
  constructor(private helper: ValidationI18nHelper) {}
  intercept(ctx: ExecutionContext, next: CallHandler) {
    const request = ctx.switchToHttp().getRequest();
    if (request.body && typeof request.body === 'object') {
      this.helper.assignMeta(request.body);
    }
    return next.handle();
  }
}

main.ts 注册:app.useGlobalInterceptors(new I18nValidationInterceptor(...))

步骤三:在 DTO 里写带 key 的 message
4. 统一文案放在 json 文件
locales/zh-CN/validation.json

{
  "username": {
    "isNotEmpty": "用户名不能为空",
    "isString": "用户名必须是字符串"
  }
}

locales/en-US/validation.json

{
  "username": {
    "isNotEmpty": "Username is required",
    "isString": "Username must be a string"
  }
}
  1. DTO 示例
export class CreateUserDto {
  @IsNotEmpty({ message: (args) => `validation.username.isNotEmpty` })
  @IsString({ message: (args) => `validation.username.isString` })
  username: string;
}

步骤四:异常过滤器兜底
6. 如果业务层手动抛 BadRequestException,也统一走同一套 i18n

catch(exception: BadRequestException, host: ArgumentsHost) {
  const lang = host.getArgs()[0].headers['x-lang'] || 'zh-CN';
  const msg = this.i18n.t(exception.message, lang);
  return response.status(400).json({ code: 40001, msg, data: null });
}

结果:
请求头 X-Lang: en-US
返回

{
  "code": 40001,
  "msg": "Username is required",
  "data": null
}

切换 X-Lang: zh-CN,提示自动变为“用户名不能为空”,全程对业务代码零侵入。

拓展思考

  1. 性能优化:ValidationPipe 默认每次 new,可以用 APP_PIPE 提供全局单例,再把语言变量挂在请求上下文(AsyncLocalStorage),避免 REQUEST 作用域带来的性能损耗。
  2. 动态枚举:错误 key 支持运行时拼接,如 validation.${field}.${rule},结合 class-validator 的 @ValidateNested 可做深层对象多语言。
  3. 前端协作:把 code 与占位符变量一起返回,如 {code:40001,msg:'',vars:{min:6,max:20}},前端可用同一套 i18n 文件做占位符替换,实现“后端只定义 key,前端控制文案”。
  4. 测试覆盖:写 e2e 用例,分别带 zh-CN、en-US、ja-JP 请求头,断言返回 msg 与预期文案完全一致,防止翻译遗漏。
  5. 微服务链路:在 gRPC 或 Kafka 消息体里带上 lang 字段,消费端继续用同一套 i18n 校验,保证全链路语言一致。