错误处理
未捕获异常与未处理 Promise 拒绝的兜底处理
捕获未捕获异常(uncaughtException)
// 全局监听未捕获异常
process.on("uncaughtException", err => {
console.error("【兜底】捕获到未处理的全局异常:", err.message);
console.error("错误调用栈:\n", err.stack);
// 关键:记录日志后,优雅退出进程(避免进程进入不稳定状态)
// 不推荐继续运行程序,因为异常可能导致资源泄露、数据不一致等问题
process.exit(1); // 退出码 1 表示异常退出
});
// 模拟未捕获异常(同步代码)
throw new Error("这是一个未被 try/catch 捕获的同步异常");
// 模拟异步代码中的未捕获同步错误(也会被 uncaughtException 捕获)
// setTimeout(() => {
// const obj = null;
// obj.name; // 抛出 TypeError,未被捕获
// }, 1000);捕获未处理 Promise 拒绝(unhandledRejection)
最后更新于