← 中文资源

简体中文版本

AggregateError 聚合校验失败

把每个字段的校验失败都收集起来,一次性抛出 AggregateError:调用方可以在一轮里看到全部错误,而不是改一个再跑一次。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

message: validation failed with 3 errors
field: email -> email is required
field: age -> age must be 18 or older
field: accepted -> terms must be accepted

实现说明

活动部件是函数 validate。 在这里做循环的是 for (const item of error.errors as FieldError[])。守卫条件成立时抛出 AggregateError,而不是返回一个假值。

使用要点

  • 守卫 errors.length > 0 满足时靠提前的 throw 短路流程。
  • 演示输出是带标签的(message:、field:),每个操作都会留下自己的一行标注。

常见问题

坏输入有失败路径吗?

守卫处(errors.length > 0)会抛出 AggregateError,非法状态到不了主逻辑。

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。 文件在加载时定义 validate。

入口签名:function validate(input: Record<string, unknown>)

核心语句

throw new AggregateError(errors, 'validation failed with ' + errors.length + ' errors');

代码示例

type FieldError = { field: string; message: string };

function validate(input: Record<string, unknown>): void {
  const errors: FieldError[] = [];

  if (typeof input.email !== 'string') {
    errors.push({ field: 'email', message: 'email is required' });
  }
  if (typeof input.age !== 'number' || input.age < 18) {
    errors.push({ field: 'age', message: 'age must be 18 or older' });
  }
  if (!input.accepted) {
    errors.push({ field: 'accepted', message: 'terms must be accepted' });
  }

  if (errors.length > 0) {
    throw new AggregateError(errors, 'validation failed with ' + errors.length + ' errors');
  }
}

try {
  validate({ email: 42, age: 16, accepted: false });
} catch (error) {
  if (error instanceof AggregateError) {
    console.log('message:', error.message);
    for (const item of error.errors as FieldError[]) {
      console.log('field:', item.field, '->', item.message);
    }
  }
}