Aggregating Failures With AggregateError

Collect every field failure and throw one AggregateError, letting callers inspect all validation errors in a single pass instead of one at a time.

TypescriptData Integrity

Code

typescriptsnippet
30 lines
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);
    }
  }
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

How it works

Aggregating Failures With AggregateError keeps everything in the function validate.

Repetition is confined to for (const item of error.errors as FieldError[]) — the rest of the file is straight-line. AggregateError is the guard’s signal — thrown at the branch, before any partial work happens.

Caveats

  • The guard errors.length > 0 short-circuits the flow with an early throw when its condition holds.

Using it

The primary signature is function validate(input: Record<string, unknown>)

Running the file prints labeled results such as message:, field: — each operation’s effect is visible in the output.

Key statements

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

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
`AggregateError` is raised at the guard (`errors.length > 0`), so invalid state never reaches the main logic.
Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. The file defines `validate` at load time.