AggregateError 与自定义错误类:构建结构化错误体系
利用 AggregateError 聚合多个错误,创建 Error 子类,设计具有堆栈追踪、错误码和元数据的健壮错误系统。 · 难度:入门 · +10XP
AggregateError 与自定义错误类:构建结构化错误体系
大部分教程只讲 throw new Error,但生产级应用需要更完善的错误处理。ES2021 引入了 AggregateError,允许将多个错误打包成一个。本课程教你如何继承 Error 创建自定义错误类型(如 ValidationError、NetworkError),附加 metadata 和错误码,并利用 AggregateError 优雅处理并发任务中的多个失败。你还会学到如何保留完整的堆栈链,以及采用 Result 模式替代传统 try/catch 提高代码健壮性。
class HttpError extends Error {
constructor(message, statusCode) {
super(message);
this.name = 'HttpError';
this.statusCode = statusCode;
}
}
async function fetchAll(urls) {
const errors = [];
const results = await Promise.allSettled(urls.map(async url => {
try {
const res = await fetch(url);
if (!res.ok) throw new HttpError('请求失败', res.status);
return res.json();
} catch (e) {
errors.push(e);
throw e;
}
}));
if (errors.length) throw new AggregateError(errors, '部分请求失败');
return results;
}