⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

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; }

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 231 篇
0 完成
🔥 0