错误处理机制
Node 错误分两类:同步错误(throw / 语法错误)可被 try/catch 捕获;异步错误分三种渠道——回调的 err 参数、Promise 的 reject、EventEmitter 的 error 事件。异步 throw 是没人接的,进程直接崩。
兜底防线是 process.on('uncaughtException') 与 unhandledRejection:它们能捕获漏网的异常,但正确做法是“记日志 + 优雅退出”,而不是假装无事发生继续跑(进程状态可能已损坏)。
- 同步错误 try/catch;Promise 错误 .catch() 或 await + try/catch
- 没人处理的 error 事件会让进程崩溃,stream 要接 error 监听
- uncaughtException 是最后防线:记录后重启,别用来兜业务逻辑
JS
// ① 回调风格:检查 err 参数 const fs = require('fs'); fs.readFile('./nope.txt', (err, data) => { if (err) return console.error('回调错误:', err.code); // ENOENT console.log(data); }); // ② Promise 风格:reject 走 catch Promise.reject(new Error('拒绝')).catch(e => console.log('接住了:', e.message)); // ③ 事件风格:error 事件必须有人监听,否则崩溃 const { EventEmitter } = require('events'); const bus = new EventEmitter(); bus.on('error', e => console.log('事件错误已处理:', e.message)); bus.emit('error', new Error('连接失败')); // ④ 最后防线(谨慎使用) process.on('uncaughtException', (e) => { console.error('漏网异常,记录后退出:', e.stack); process.exit(1); });
本节要点错误处理按渠道选家伙:回调查 err、Promise 接 catch、事件监听 error;uncaughtException 只兜底、不兜业务。




