有时我们会忽略错误处理和堆栈追踪的一些细节, 但是这些细节对于写与测试或错误处理相关的库来说是非常有用的. 例如这周, 对于 Chai 就有一个非常棒的PR, 该PR极大地改善了我们处理堆栈的方式, 当用户的断言失败的时候, 我们会给予更多的提示信息(帮助用户进行定位).

合理地处理堆栈信息能使你清除无用的数据, 而只专注于有用的数据. 同时, 当更好地理解 Errors 对象及其相关属性之后, 能有助于你更充分地利用 Errors.

(函数的)调用栈是怎么工作的

在谈论错误之前, 先要了解下(函数的)调用栈的原理:

当有一个函数被调用的时候, 它就被压入到堆栈的顶部, 该函数运行完成之后, 又会从堆栈的顶部被移除.

堆栈的数据结构就是后进先出, 以 LIFO (last in, first out) 著称.

例如:

  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 运行时, 其会被添加到堆栈的顶部. 然后, 当函数 b 在函数 a 的内部被调用时, 函数 b 会被压入到堆栈的顶部. 当函数 c 在函数 b 的内部被调用时也会被压入到堆栈的顶部.

当函数 c 运行时, 堆栈中就包含了 a, b 和 c(按此顺序).

当函数 c 运行完毕之后, 就会从堆栈的顶部被移除, 然后函数调用的控制流就回到函数 b. 函数 b 运行完之后, 也会从堆栈的顶部被移除, 然后函数调用的控制流就回到函数 a. 最后, 函数 a 运行完成之后也会从堆栈的顶部被移除.

为了更好地在demo中演示堆栈的行为, 可以使用 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 的 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 // <-- For now feel free to ignore anything below this point, these are Node's internals
  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 中输出时, 堆栈中包含了函数 a, b 以及c.

如果在函数 c 运行完成之后, 在函数 b 中输出当前的堆栈数据, 就会看到函数 c 已经从堆栈的顶部被移除, 此时堆栈中仅包括函数 a 和 b.

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

正如所看到的, 函数 c 运行完成之后, 已经从堆栈的顶部被移除.

  1. Trace
  2. at b (repl:4:9)
  3. at a (repl:3:1)
  4. at repl:1:1  // <-- For now feel free to ignore anything below this point, these are Node's internals
  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–错误的名字(类型)

上述是 Error.prototype 的标准属性, 此外, 不同的运行环境都有其特定的属性. 在例如 Node, Firefox, Chrome, Edge, IE 10+, Opera 以及 Safari 6+ 这样的环境中, Error 对象具备 stack 属性, 该属性包含了错误的堆栈轨迹. 一个错误实例的堆栈轨迹包含了自构造函数之后的所有堆栈结构.

如果想了解更多关于 Error 对象的特定属性, 可以阅读 MDN 上的这篇文章.

为了抛出一个错误, 必须使用 throw 关键字. 为了 catch 一个抛出的错误, 必须使用 try...catch 包含可能跑出错误的代码. Catch的参数是被跑出的错误实例.

如 Java 一样, JavaScript 也允许在 try/catch 之后使用 finally 关键字. 在处理完错误之后, 可以在finally 语句块作一些清除工作.

在语法上, 你可以使用 try 语句块而其后不必跟着 catch 语句块, 但必须跟着 finally 语句块. 这意味着有三种不同的 try 语句形式:

  • try...catch
  • try...finally
  • try...catch...finally

Try语句内还可以在嵌入 try 语句:

  1. try {
  2. try {
  3. throw new Error('Nested error.'); // The error thrown here will be caught by its own `catch` clause
  4. } catch (nestedErr) {
  5. console.log('Nested catch'); // This runs
  6. }
  7. } catch (err) {
  8. console.log('This will not run.');
  9. }

也可以在 catch 或 finally 中嵌入 try 语句:

  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 的参数抛出了一个错误对象, 上面的代码能正常捕获错误. 然后, 如果是抛出一个字符串, 就会碰到一些问题了:

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

现在第二个 console.log 会输出undefined. 这看起来不是很重要, 但如果你需要确保 Error 对象有一个特定的属性或者用另一种方式来处理 Error 对象的特定属性(例如 Chai的throws断言的做法), 你就得做大量的工作来确保程序的正确运行.

同时, 如果抛出的不是 Error 对象, 也就获取不到 stack 属性.

Errors 也可以被作为其它对象, 你也不必抛出它们, 这也是为什么大多数回调函数把 Errors 作为第一个参数的原因. 例如:

  1. const fs = require('fs');
  2. fs.readdir('/example/i-do-not-exist', function callback(err, dirs) {
  3. if (err instanceof Error) {
  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 对象也可以用于 rejected promise, 这使得很容易处理 rejected 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. });

处理堆栈

这一节是针对支持 Error.captureStackTrace的运行环境, 例如Nodejs.

Error.captureStackTrace 的第一个参数是 object, 第二个可选参数是一个 function.Error.captureStackTrace 会捕获堆栈信息, 并在第一个参数中创建 stack 属性来存储捕获到的堆栈信息. 如果提供了第二个参数, 该函数将作为堆栈调用的终点. 因此, 捕获到的堆栈信息将只显示该函数调用之前的信息.

用下面的两个demo来解释一下. 第一个, 仅将捕获到的堆栈信息存于一个普通的对象之中:

  1. const myObj = {};
  2. function c() {
  3. }
  4. function b() {
  5. // Here we will store the current stack trace into myObj
  6. Error.captureStackTrace(myObj);
  7. c();
  8. }
  9. function a() {
  10. b();
  11. }
  12. // First we will call these functions
  13. a();
  14. // Now let's see what is the stack trace stored into myObj.stack
  15. console.log(myObj.stack);
  16. // This will print the following stack to the console:
  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(被压入堆栈), 然后在 a 里面调用函数 b(被压入堆栈且在a之上), 然后在 b 中捕获到当前的堆栈信息, 并将其存储到 myObj 中. 所以, 在控制台输出的堆栈信息中仅包含了 a和 b 的调用信息.

现在, 我们给 Error.captureStackTrace 传递一个函数作为第二个参数, 看下输出信息:

  1. const myObj = {};
  2. function d() {
  3. // Here we will store the current stack trace into myObj
  4. // This time we will hide all the frames after `b` and `b` itself
  5. Error.captureStackTrace(myObj, b);
  6. }
  7. function c() {
  8. d();
  9. }
  10. function b() {
  11. c();
  12. }
  13. function a() {
  14. b();
  15. }
  16. // First we will call these functions
  17. a();
  18. // Now let's see what is the stack trace stored into myObj.stack
  19. console.log(myObj.stack);
  20. // This will print the following stack to the console:
  21. //    at a (repl:2:1) <-- As you can see here we only get frames before `b` was called
  22. //    at repl:1:1 <-- Node internals below this line
  23. //    at realRunInThisContextScript (vm.js:22:35)
  24. //    at sigintHandlersWrap (vm.js:98:12)
  25. //    at ContextifyScript.Script.runInThisContext (vm.js:24:12)
  26. //    at REPLServer.defaultEval (repl.js:313:29)
  27. //    at bound (domain.js:280:14)
  28. //    at REPLServer.runBound [as eval] (domain.js:293:12)
  29. //    at REPLServer.onLine (repl.js:513:10)
  30. //    at emitOne (events.js:101:20)

当将函数 b 作为第二个参数传给 Error.captureStackTraceFunction 时, 输出的堆栈就只包含了函数 b 调用之前的信息(尽管 Error.captureStackTraceFunction 是在函数 d 中调用的), 这也就是为什么只在控制台输出了 a. 这样处理方式的好处就是用来隐藏一些与用户无关的内部实现细节.

作者:佚名

来源:51CTO

JavaScript错误处理和堆栈追踪浅析相关推荐

  1. Java语法与架构中的异常处理(assert断言、堆栈追踪)

    程序中总有些意想不到的状况所引发的错误,Java中的错误也以对象方式呈现为java.lang.Throwable的各种子类实例.只要你能捕捉包装错误的对象,就可以针对该错误做一些处理,例如,试恢复正常 ...

  2. 深入理解 JavaScript 错误和堆栈追踪

    有时候人们并不关注这些细节,但这方面的知识肯定有用,尤其是当你正在编写与测试或errors相关的库.例如这个星期我们的chai中出现了一个令人惊叹的Pull Request,它大大改进了我们处理堆栈跟 ...

  3. javascript错误_JavaScript开发人员最常犯的10个错误

    javascript错误 常见错误1:对" this'错误引用 (Common Mistake #1: Incorrect references to 'this') As JavaScri ...

  4. Javascript错误处理——try...catch

    Javascript错误处理--try-catch 无论我们编程多么精通,脚本错误怎是难免.可能是我们的错误造成,或异常输入,错误的服务器端响应以及无数个其他原因. 通常,当发送错误时脚本会立刻停止, ...

  5. IE调试网页之五:使用 F12 开发人员工具调试 JavaScript 错误 (Windows)

    使用 F12 开发人员工具,Web 开发人员能够在无需离开浏览器的情况下快速调试 JavaScript 代码. 通过内置到每个 Windows Internet Explorer 9 安装中,F12 ...

  6. 10 种最常见的 Javascript 错误 — 总结于 1000+ 个项目,并阐述如何避免

    引用 原文地址: https://rollbar.com/blog/top-10-javascript-errors/  更多文章参见:  https://github.com/elevenbeans ...

  7. 什么是堆栈追踪(StackTrace)?如何利用StackTrace对程序进行调试?

    有时候你在运行程序时可能会出现如下错误: Exception in thread "main" java.lang.NullPointerExceptionat com.examp ...

  8. 浅谈JavaScript错误

    本文主要从前端开发者的角度谈一谈大多数前端开发者都会遇到的js错误,对错误产生的原因.发生阶段,以及如何应对错误进行分析.归纳和总结,希望得到一些有益的结论用来指导日常开发工作. 概念辨析 错误(Er ...

  9. javascript 错误与调试

    1.JavaScript 错误 - throw.try 和 catch try 语句测试代码块的错误. catch 语句处理错误. throw 语句创建自定义错误. 1.1 JavaScript 错误 ...

最新文章

  1. 每日两SQL(5),欢迎交流~
  2. 如何使用我的博客电子书
  3. HDU4911 Inversion 解题报告
  4. 微服务开发及部署_基于 Kubernetes 的微服务部署即代码
  5. MySQL系列(三)
  6. android开发歌词滑动效果_漂亮的Android音乐歌词控件 仿网易云音乐滑动效果
  7. netty做一个posp的网络_Java网络通信基础系列-Netty实现HTTP服务
  8. Android打开系统自带文件管理器,全选菜单选项
  9. Eclipse/Myeclipse自定义JSP模板
  10. 格雷码算法c语言实验报告,算法设计与分析实验报告
  11. 天地波超视距雷达在远洋无人航运中的运用
  12. 《置身事内》读书笔记第一章 地方政府的权利与事务
  13. 智慧停车场综合解决方案
  14. 用正则表达式将文字转换成表情图片
  15. 【论文阅读】自然语言生成(NLG)——基于plan思想的Data2Text任务实现
  16. 【Qualcomm高通音频】如何区分配置ECM驻极体麦克风和MEMS硅麦克风
  17. 2022 年InfoWorld 精选最佳开源软件
  18. 实录:余凯、颜水成、梅涛、张兆翔、山世光同台讨论 “深度学习的能与不能”
  19. 从移动2G、3G、4G和iphone5s说起的手机那点事
  20. Python实现经典机器学习案例 良/恶性性乳腺癌肿瘤预测

热门文章

  1. 系统提示一个程序正在被另一个程序调用,如何知道是被哪个程序调用
  2. popupmenu java_Java基于JPopupMenu实现系统托盘的弹出菜单,解决PopupMenu弹出菜单中文乱码...
  3. 9月计算机一级报名入口,北京市2018年9月计算机一级报名时间|网上报名入口【已正式开通】...
  4. mesh和wifi中继的区别_深度解读Mesh路由和无线中继的差异,谁才是性价比之选?...
  5. 32位mysql安装包_软件测试基础——Linux系统搭建MySQL数据库
  6. java输出一副扑克牌_JAVA编一副扑克牌
  7. springboot和springcloud有什么关系
  8. Redis-benchmark测试Redis性能
  9. 了解这些后设计输入框原来这么简单
  10. 2020程序员人群洞察报告