多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
&emsp;&emsp;在 Node.js 中,提供了[error](https://nodejs.org/dist/latest-v18.x/docs/api/errors.html)模块,并且内置了标准的 JavaScript 错误,常见的有: * EvalError:在调用 eval() 函数时出现问题时抛出该错误。 * SyntaxError:调用不符合 JavaScript 的语法时抛出该错误。 * RangeError:超出可接受值的集合或范围,例如数组越界。 * ReferenceError:访问未定义的变量时抛出该错误。 * TypeError:参数或变量的类型有问题时抛出该错误。 * URIError:使用全局的 URI 处理函数发生问题时抛出该错误。 &emsp;&emsp;本系列所有的示例源码都已上传至Github,[点击此处](https://github.com/pwstrick/node)获取。  ## 一、Error 类 &emsp;&emsp;Node.js 生成的上述错误,都是 Error 类的实例或继承自 Error 类。注意,运行时抛出的所有异常都将是 Error 的实例。 &emsp;&emsp;Error 实例能捕获堆栈跟踪,并提供错误的文本描述。 &emsp;&emsp;下面是一个简单的示例,其中 message 属性提供了错误的字符串描述,toString() 会生成文本消息。 &emsp;&emsp;stack 属性提供了完整的错误信息,包括错误描述和一系列堆栈帧(每行以 "at " 开头),每一帧都描述了代码中生成错误的调用点。 ~~~ const e = new Error('test error'); // test error console.log(e.message); // Error: test error console.log(e.toString()); // Error: test error // at Object.<anonymous> (/Users/code/web/node/08/error.js:1:11) // at Module._compile (node:internal/modules/cjs/loader:1108:14) // at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10) // at Module.load (node:internal/modules/cjs/loader:988:32) // at Function.Module._load (node:internal/modules/cjs/loader:828:14) // at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) // at node:internal/main/run_main_module:17:47 console.log(e.stack); ~~~ ## 二、捕获错误 &emsp;&emsp;一些异常在 JavaScript 层是不可恢复的,会导致 Node.js 进程崩溃。 &emsp;&emsp;所以有些异常需要被捕获,在 Node.js 中有 3 种常用的捕获方法: * 错误优先的回调。 * throw 语句或 try-catch 语句。 * error 事件机制。 **1)错误优先的回调** &emsp;&emsp;Node.js 核心模块暴露的大多数异步方法都遵循错误优先回调的惯用模式。 &emsp;&emsp;使用这种模式,回调函数作为参数传给方法,当操作完成或出现错误时,回调函数将使用 Error 实例作为第一个参数传入。 &emsp;&emsp;如果没有出现错误,则第一个参数将作为 null 传入。在下面的示例中,当读取一个不存在的文件时,将抛出错误。 ~~~ const fs = require('fs'); function errorCallback(err, data) { // [Error: ENOENT: no such file or directory, open './data.txt'] { // errno: -2, // code: 'ENOENT', // syscall: 'open', // path: './data.txt' // } console.log(err); } fs.readFile('./data.txt', errorCallback); ~~~ **2)throw** &emsp;&emsp;throw 关键字后面可以跟任何类型的 JavaScript 值(字符串、数字或对象等)。 &emsp;&emsp;不过在 Node.js 中,throw 不会抛出字符串,而仅抛出 Error 实例。 &emsp;&emsp;直接抛出 Error 实例,和抛出其他类型的值,前者会显示堆栈帧,而后者不会,如下所示。 ~~~ // /Users/code/web/node/08/throw.js:2 // throw new Error('test error'); // ^ // Error: test error // at test (/Users/code/web/node/08/throw.js:2:9) // at Object.<anonymous> (/Users/code/web/node/08/throw.js:7:1) // at Module._compile (node:internal/modules/cjs/loader:1108:14) // at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10) // at Module.load (node:internal/modules/cjs/loader:988:32) // at Function.Module._load (node:internal/modules/cjs/loader:828:14) // at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) // at node:internal/main/run_main_module:17:47 throw new Error('test error'); // /Users/code/web/node/08/throw.js:2 // throw 'test error'; // ^ // test error // (Use `node --trace-uncaught ...` to show where the exception was thrown) throw 'test error'; ~~~ **3)try-catch** &emsp;&emsp;try-catch 语句不仅能捕获同步代码,还能捕获异步的 async/await 发生的错误,如下所示,调用一个不存在的 func() 函数。 ~~~ // 同步代码 function try1() { try{ func(); }catch(e) { console.log(e); console.log('try-catch end'); } } // async/await async function test() { func(); } async function try2() { try{ await test(); }catch(e) { console.log(e); console.log('async try-catch end'); } } ~~~ &emsp;&emsp;有一点需要注意,try-catch 无法捕获异步的回调函数,例如定时器、process.nextTick() 中的回调。 ~~~ try { process.nextTick(function () { func(); }); } catch (e) { console.log('nextTick end'); } ~~~ &emsp;&emsp;catch 分支中的打印并不会执行,因为当回调被调用时,周围的代码(包括 try-catch)都已经运行好退出了。 **4)error 事件机制** &emsp;&emsp;如果在程序执行过程中出现了未捕获的异常,那么程序就会崩溃,Node.js 提供了几个事件来兜底这类未捕获的异常。 &emsp;&emsp;首先是 process 上的[uncaughtException](https://nodejs.org/dist/latest-v18.x/docs/api/process.html#event-uncaughtexception)事件,当未捕获的 JavaScript 异常冒泡到事件循环时,就会自动触发该事件。 &emsp;&emsp;就比如上面那个无法捕获的 try-catch 问题,注册了 uncaughtException 事件就能成功捕获,如下所示。 ~~~ // ReferenceError: func is not defined // at /Users/code/web/node/08/uncaughtException.js:7:5 // at processTicksAndRejections (node:internal/process/task_queues:78:11) process.on('uncaughtException', (err) => { console.log(err); }); ~~~ &emsp;&emsp;在捕获后,就不会让程序奔溃,后续代码也能被顺利运行。 &emsp;&emsp;注意,uncaughtException 事件是用于异常处理的粗略机制,仅用作最后的兜底手段,归根结底,那些异常不能无视还是需要修复的。 &emsp;&emsp;使用 Promise 进行编程时,异常被封装为“被拒绝的 promise”,有两种捕获方式。第一种是使用 promise.catch() 捕获和处理,并通过 Promise 链传播。 &emsp;&emsp;第二种是注册 process 的[unhandledRejection](https://nodejs.org/dist/latest-v18.x/docs/api/process.html#event-unhandledrejection)事件,当 Promise 被拒绝并且在事件循环的一个轮询内没有错误捕获时,就会触发此事件。 &emsp;&emsp;unhandledRejection 事件回调程序包含两个参数,第一个是任意类型的 Promise 被拒绝的理由,第二个是被拒绝的 Promise 对象。 ~~~ process.on('unhandledRejection', (reason, promise) => { console.log(reason); console.log(promise); }); ~~~ &emsp;&emsp;下面是两种触发方式,第一种是在 then() 回调中书写错误代码,第二种是绑定 reject() 方法。 ~~~ // 第一种触发方式 Promise.resolve().then((res) => { return JSON.pasre(res); // 注意错别字 pasre }); // 第二种触发方式 Promise.reject(new Error('资源尚未加载')); ~~~ &emsp;&emsp;unhandledRejection 事件对于检测和跟踪尚未处理的被拒绝的 Promise 很有用。 **5)verror** &emsp;&emsp;在下面的示例中,会在异步回调中通过 throw 抛出一个错误。 ~~~ function test() { throw new Error('test error'); } function main() { setImmediate(() => test()); } main(); ~~~ &emsp;&emsp;注意观察下面的堆栈信息,仅仅标注了 test() 函数中出错的那条语句的位置,但是再往上的 main() 并没有被标注。 ~~~ /Users/code/web/node/08/verror.js:2 throw new Error('test error'); ^ Error: test error at test (/Users/code/web/node/08/verror.js:2:9) at Immediate.<anonymous> (/Users/code/web/node/08/verror.js:5:22) at processImmediate (node:internal/timers:464:21) ~~~ &emsp;&emsp;当函数的调用深度比较深时,一旦出错,那么追溯程序完整的执行过程就比较困难。 &emsp;&emsp;目前市面上有一款[verror](https://github.com/TritonDataCenter/node-verror)库,可以将 Error 实例层层封装,在每一层附加错误信息,最后通过 VError 实例就能获取调试所需的信息,便于问题的定位。 ~~~ const VError = require('verror'); function test(err) { const err3 = new VError(err, 'test()'); console.log(err3.message); // test(): main(): test error console.log(err3); } function main() { setImmediate(() => { const err1 = new Error('test error'); const err2 = new VError(err1, 'main()'); test(err2); }); } main(); ~~~ &emsp;&emsp;在上面的示例中,先实例化一个 Error 类,然后实例化一个 VError 类,构造函数的第二个参数就是提供给调试用的关键信息。 &emsp;&emsp;将 VError 实例作为参数传递给 test() 函数,再实例化一个 VError 类,这其实就是层层包装的过程。 &emsp;&emsp;最后读取 message 属性,得到的值是 test(): main(): test error,这些就是附加的数据,以及错误描述。 &emsp;&emsp;如果直接打印 VError 实例,那么能得到更多关键信息,包括行数,文件路径等。 ~~~ VError: test(): main(): test error at test (/Users/code/web/node/08/verror.js:3:16) at Immediate._onImmediate (/Users/code/web/node/08/verror.js:11:5) at processImmediate (node:internal/timers:464:21) { jse_shortmsg: 'test()', jse_cause: VError: main(): test error at Immediate._onImmediate (/Users/code/web/node/08/verror.js:10:18) at processImmediate (node:internal/timers:464:21) { jse_shortmsg: 'main()', jse_cause: Error: test error at Immediate._onImmediate (/Users/code/web/node/08/verror.js:9:18) at processImmediate (node:internal/timers:464:21), jse_info: {} }, jse_info: {} } ~~~ 参考资料: [捕获异常](https://www.nodejs.red/#/nodejs/advanced/uncaugh-exception) [诊断报告](https://www.nodejs.red/#/nodejs/modules/report)  [饿了么调试面试题](https://github.com/ElemeFE/node-interview/tree/master/sections/zh-cn#%E9%94%99%E8%AF%AF%E5%A4%84%E7%90%86%E8%B0%83%E8%AF%95) [\[译\] NodeJS 错误处理最佳实践](https://cnodejs.org/topic/55714dfac4e7fbea6e9a2e5d) [异常处理与domain](https://yjhjstz.gitbooks.io/deep-into-node/content/chapter13/chapter13-2.html) ***** > 原文出处: [博客园-Node.js精进](https://www.cnblogs.com/strick/category/2154090.html) [知乎专栏-前端性能精进](https://www.zhihu.com/column/c_1611672656142725120) 已建立一个微信前端交流群,如要进群,请先加微信号freedom20180706或扫描下面的二维码,请求中需注明“看云加群”,在通过请求后就会把你拉进来。还搜集整理了一套[面试资料](https://github.com/pwstrick/daily),欢迎浏览。 ![](https://box.kancloud.cn/2e1f8ecf9512ecdd2fcaae8250e7d48a_430x430.jpg =200x200) 推荐一款前端监控脚本:[shin-monitor](https://github.com/pwstrick/shin-monitor),不仅能监控前端的错误、通信、打印等行为,还能计算各类性能参数,包括 FMP、LCP、FP 等。