找回密码
 立即注册

QQ登录

只需一步,快速开始

断天涯大虾
社区贡献组   /  发表于:2017-3-30 09:57  /   查看:3980  /  回复:0
本帖最后由 断天涯大虾 于 2017-3-30 10:09 编辑

大多数工程师可能并没留意过 JS 中错误对象、错误堆栈的细节,即使他们每天的日常工作会面临不少的报错,部分同学甚至在 console 的错误面前一脸懵逼,不知道从何开始排查,如果你对本文讲解的内容有系统的了解,就会从容很多。而错误堆栈清理能让你有效去掉噪音信息,聚焦在真正重要的地方,此外,如果理解了 Error 的各种属性到底是什么,你就能更好的利用他。

接下来,我们就直奔主题。


调用栈的工作机制
在探讨 JS 中的错误之前,我们必须理解调用栈(Call Stack)的工作机制,其实这个机制非常简单,如果你对这个已经一清二楚了,可以直接跳过这部分内容。

简单的说:函数被调用时,就会被加入到调用栈顶部,执行结束之后,就会从调用栈顶部移除该函数,这种数据结构的关键在于后进先出,即大家所熟知的 LIFO。比如,当我们在函数y内部调用函数 x 的时候,调用栈从下往上的顺序就是 y->x 。

我们再举个代码实例:
  1. function c() {
  2.     console.log('c');
  3. }

  4. function b() {
  5.     console.log('b');
  6.     c();
  7. }

  8. function a() {
  9.     console.log('a');
  10.     b();
  11. }

  12. a();
复制代码
这段代码运行时,首先 a 会被加入到调用栈的顶部,然后,因为 a 内部调用了 b,紧接着 b 被加入到调用栈的顶部,当 b 内部调用 c 的时候也是类似的。在调用 c的时候,我们的调用栈从下往上会是这样的顺序:a -> b -> c。在 c 执行完毕之后,c 被从调用栈中移除,控制流回到 b 上,调用栈会变成:a -> b,然后 b 执行完之后,调用栈会变成:a,当 a 执行完,也会被从调用栈移除。

为了更好的说明调用栈的工作机制,我们对上面的代码稍作改动,使用 console.trace 来把当前的调用栈输出到 console 中,你可以认为console.trace 打印出来的调用栈的每一行出现的原因是它下面的那行调用而引起的。
  1. function c() {
  2.     console.log('c');
  3.     console.trace();
  4. }

  5. function b() {
  6.     console.log('b');
  7.     c();
  8. }

  9. function a() {
  10.     console.log('a');
  11.     b();
  12. }

  13. a();
复制代码
当我们在 Node.js 的 REPL 中运行这段代码,会得到如下的结果:
  1. Trace
  2.     at c (repl:3:9)
  3.     at b (repl:3:1)
  4.     at a (repl:3:1)
  5.     at repl:1:1 // <-- 从这行往下的内容可以忽略,因为这些都是 Node 内部的东西
  6.     at realRunInThisContextScript (vm.js:22:35)
  7.     at sigintHandlersWrap (vm.js:98:12)
  8.     at ContextifyScript.Script.runInThisContext (vm.js:24:12)
  9.     at REPLServer.defaultEval (repl.js:313:29)
  10.     at bound (domain.js:280:14)
  11.     at REPLServer.runBound [as eval] (domain.js:293:12)
复制代码
显而易见,当我们在 c 内部调用 console.trace 的时候,调用栈从下往上的结构是:a -> b -> c。如果把代码再稍作改动,在 b 中 c 执行完之后调用,如下:
  1. function c() {
  2.     console.log('c');
  3. }

  4. function b() {
  5.     console.log('b');
  6.     c();
  7.     console.trace();
  8. }

  9. function a() {
  10.     console.log('a');
  11.     b();
  12. }

  13. a();
复制代码
通过输出结果可以看到,此时打印的调用栈从下往上是:a -> b,已经没有 c 了,因为 c 执行完之后就从调用栈移除了。
  1. Trace
  2.     at b (repl:4:9)
  3.     at a (repl:3:1)
  4.     at repl:1:1  // <-- 从这行往下的内容可以忽略,因为这些都是 Node 内部的东西
  5.     at realRunInThisContextScript (vm.js:22:35)
  6.     at sigintHandlersWrap (vm.js:98:12)
  7.     at ContextifyScript.Script.runInThisContext (vm.js:24:12)
  8.     at REPLServer.defaultEval (repl.js:313:29)
  9.     at bound (domain.js:280:14)
  10.     at REPLServer.runBound [as eval] (domain.js:293:12)
  11.     at REPLServer.onLine (repl.js:513:10)
复制代码
再总结下调用栈的工作机制:调用函数的时候,会被推到调用栈的顶部,而执行完毕之后,就会从调用栈移除。                                                                                                                                                                                                                                                                                               
Error 对象及错误处理
当代码中发生错误时,我们通常会抛出一个 Error 对象。Error 对象可以作为扩展和创建自定义错误类型的原型。Error 对象的 prototype 具有以下属性:
  • constructor – 负责该实例的原型构造函数;
  • message – 错误信息;
  • name – 错误的名字;

上面都是标准属性,有些 JS 运行环境还提供了标准属性之外的属性,如 Node.js、Firefox、Chrome、Edge、IE 10、Opera 和 Safari 6+ 中会有 stack 属性,它包含了错误代码的调用栈,接下来我们简称错误堆栈。错误堆栈包含了产生该错误时完整的调用栈信息。如果您想了解更多关于 Error 对象的非标准属性,我强烈建议你阅读 MDN 的这篇文章

抛出错误时,你必须使用 throw 关键字。为了捕获抛出的错误,则必须使用 try catch 语句把可能出错的代码块包起来,catch 的时候可以接收一个参数,该参数就是被抛出的错误。与 Java 中类似,JS 中也可以在 try catch 语句之后有 finally,不论前面代码是否抛出错误 finally 里面的代码都会执行,这种语言的常见用途有:在 finally 中做些清理的工作。

此外,你可以使用没有 catch 的 try 语句,但是后面必须跟上 finally,这意味着我们可以使用三种不同形式的 try 语句:
  • try … catch
  • try … finally
  • try … catch … finally
try 语句还可以嵌套在 try 语句中,比如:
  1. try {
  2.     try {
  3.         throw new Error('Nested error.'); // 这里的错误会被自己紧接着的 catch 捕获
  4.     } catch (nestedErr) {
  5.         console.log('Nested catch'); // 这里会运行
  6.     }
  7. } catch (err) {
  8.     console.log('This will not run.');  // 这里不会运行
  9. }
复制代码
try 语句也可以嵌套在 catch 和 finally 语句中,比如下面的两个例子:
  1. try {
  2.     throw new Error('First error');
  3. } catch (err) {
  4.     console.log('First catch running');
  5.     try {
  6.         throw new Error('Second error');
  7.     } catch (nestedErr) {
  8.         console.log('Second catch running.');
  9.     }
  10. }
复制代码
  1. try {
  2.     console.log('The try block is running...');
  3. } finally {
  4.     try {
  5.         throw new Error('Error inside finally.');
  6.     } catch (err) {
  7.         console.log('Caught an error inside the finally block.');
  8.     }
  9. }
复制代码
同样需要注意的是,你可以抛出不是 Error 对象的任意值。这可能看起来很酷,但在工程上却是强烈不建议的做法。如果恰巧你需要处理错误的调用栈信息和其他有意义的元数据,抛出非 Error 对象的错误会让你的处境很尴尬。

假如我们有如下的代码:
  1. function runWithoutThrowing(func) {
  2.     try {
  3.         func();
  4.     } catch (e) {
  5.         console.log('There was an error, but I will not throw it.');
  6.         console.log('The error\'s message was: ' + e.message)
  7.     }
  8. }

  9. function funcThatThrowsError() {
  10.     throw new TypeError('I am a TypeError.');
  11. }

  12. runWithoutThrowing(funcThatThrowsError);
复制代码
如果 runWithoutThrowing 的调用者传入的函数都能抛出 Error 对象,这段代码不会有任何问题,如果他们抛出了字符串那就有问题了,比如:
  1. function runWithoutThrowing(func) {
  2.     try {
  3.         func();
  4.     } catch (e) {
  5.         console.log('There was an error, but I will not throw it.');
  6.         console.log('The error\'s message was: ' + e.message)
  7.     }
  8. }

  9. function funcThatThrowsString() {
  10.     throw 'I am a String.';
  11. }

  12. runWithoutThrowing(funcThatThrowsString);
复制代码
这段代码运行时,runWithoutThrowing 中的第 2 次 console.log 会抛出错误,因为 e.message 是未定义的。这些看起来似乎没什么大不了的,但如果你的代码需要使用 Error 对象的某些特定属性,那么你就需要做很多额外的工作来确保一切正常。如果你抛出的值不是 Error 对象,你就不会拿到错误相关的重要信息,比如 stack,虽然这个属性在部分 JS 运行环境中才会有。

Error 对象也可以向其他对象那样使用,你可以不用抛出错误,而只是把错误传递出去,Node.js 中的错误优先回调就是这种做法的典型范例,比如 Node.js 中的 fs.readdir 函数:
  1. const fs = require('fs');

  2. fs.readdir('/example/i-do-not-exist', function callback(err, dirs) {
  3.     if (err) {
  4.         // `readdir` will throw an error because that directory does not exist
  5.         // We will now be able to use the error object passed by it in our callback function
  6.         console.log('Error Message: ' + err.message);
  7.         console.log('See? We can use Errors without using try statements.');
  8.     } else {
  9.         console.log(dirs);
  10.     }
  11. });
复制代码
此外,Error 对象还可以用于 Promise.reject 的时候,这样可以更容易的处理 Promise 失败,比如下面的例子:
  1. new Promise(function(resolve, reject) {
  2.     reject(new Error('The promise was rejected.'));
  3. }).then(function() {
  4.     console.log('I am an error.');
  5. }).catch(function(err) {
  6.     if (err instanceof Error) {
  7.         console.log('The promise was rejected with an error.');
  8.         console.log('Error Message: ' + err.message);
  9.     }
  10. });
复制代码


错误堆栈的裁剪
Node.js 才支持这个特性,通过 Error.captureStackTrace 来实现,Error.captureStackTrace 接收一个 object 作为第 1 个参数,以及可选的 function 作为第 2 个参数。其作用是捕获当前的调用栈并对其进行裁剪,捕获到的调用栈会记录在第 1 个参数的 stack 属性上,裁剪的参照点是第 2 个参数,也就是说,此函数之前的调用会被记录到调用栈上面,而之后的不会。

让我们用代码来说明,首先,把当前的调用栈捕获并放到 myObj 上:
  1. const myObj = {};

  2. function c() {
  3. }

  4. function b() {
  5.     // 把当前调用栈写到 myObj 上
  6.     Error.captureStackTrace(myObj);
  7.     c();
  8. }

  9. function a() {
  10.     b();
  11. }

  12. // 调用函数 a
  13. a();

  14. // 打印 myObj.stack
  15. console.log(myObj.stack);

  16. // 输出会是这样
  17. //    at b (repl:3:7) <-- Since it was called inside B, the B call is the last entry in the stack
  18. //    at a (repl:2:1)
  19. //    at repl:1:1 <-- Node internals below this line
  20. //    at realRunInThisContextScript (vm.js:22:35)
  21. //    at sigintHandlersWrap (vm.js:98:12)
  22. //    at ContextifyScript.Script.runInThisContext (vm.js:24:12)
  23. //    at REPLServer.defaultEval (repl.js:313:29)
  24. //    at bound (domain.js:280:14)
  25. //    at REPLServer.runBound [as eval] (domain.js:293:12)
  26. //    at REPLServer.onLine (repl.js:513:10)
复制代码
上面的调用栈中只有 a -> b,因为我们在 b 调用 c 之前就捕获了调用栈。现在对上面的代码稍作修改,然后看看会发生什么:
  1. const myObj = {};

  2. function d() {
  3.     // 我们把当前调用栈存储到 myObj 上,但是会去掉 b 和 b 之后的部分
  4.     Error.captureStackTrace(myObj, b);
  5. }

  6. function c() {
  7.     d();
  8. }

  9. function b() {
  10.     c();
  11. }

  12. function a() {
  13.     b();
  14. }

  15. // 执行代码
  16. a();

  17. // 打印 myObj.stack
  18. console.log(myObj.stack);

  19. // 输出如下
  20. //    at a (repl:2:1) <-- As you can see here we only get frames before `b` was called
  21. //    at repl:1:1 <-- Node internals below this line
  22. //    at realRunInThisContextScript (vm.js:22:35)
  23. //    at sigintHandlersWrap (vm.js:98:12)
  24. //    at ContextifyScript.Script.runInThisContext (vm.js:24:12)
  25. //    at REPLServer.defaultEval (repl.js:313:29)
  26. //    at bound (domain.js:280:14)
  27. //    at REPLServer.runBound [as eval] (domain.js:293:12)
  28. //    at REPLServer.onLine (repl.js:513:10)
  29. //    at emitOne (events.js:101:20)
复制代码
在这段代码里面,因为我们在调用 Error.captureStackTrace 的时候传入了 b,这样 b 之后的调用栈都会被隐藏。

现在你可能会问,知道这些到底有啥用?如果你想对用户隐藏跟他业务无关的错误堆栈(比如某个库的内部实现)就可以试用这个技巧。


总结
通过本文的描述,相信你对 JS 中的调用栈、Error 对象、错误堆栈有了清晰的认识,在遇到错误的时候不在慌乱。如果对文中的内容有任何疑问,欢迎在下面评论。

   
关于葡萄城:全球最大的控件提供商,世界领先的企业应用定制工具、企业报表和商业智能解决方案提供商,为超过75%的全球财富500强企业提供服务。

1 个回复

倒序浏览
您需要登录后才可以回帖 登录 | 立即注册
返回顶部