π Prefer AggregateError when throwing collected errors.
πΌ This rule is enabled in the following configs: β
recommended, βοΈ unopinionated.
π§ This rule is automatically fixable by the --fix CLI option.
This rule enforces using AggregateError when a collected array of Error instances or built-in Error subclasses is checked before throwing a generic Error.
AggregateError keeps the collected errors available on the thrown error instead of losing them behind a summary message.
The rule intentionally targets only direct guarded throws where the collection name clearly refers to errors and the error collection is evident from TypeScript annotations or type information. Custom error subclasses require type information. More indirect collection flow is ignored.
// β
const errors: Error[] = [new Error('Email is required.')];
if (errors.length > 0) {
throw new Error('Validation failed.');
}
// β
const errors: Error[] = [new Error('Email is required.')];
if (errors.length > 0) {
throw new AggregateError(errors, 'Validation failed.');
}// β
const validationErrors: TypeError[] = [new TypeError('Invalid email.')];
if (validationErrors.length !== 0) {
throw new Error('Validation failed.', {cause});
}
// β
const validationErrors: TypeError[] = [new TypeError('Invalid email.')];
if (validationErrors.length !== 0) {
throw new AggregateError(validationErrors, 'Validation failed.', {cause});
}