作家
登录

JavaScript错误处理和堆栈追踪浅析

作者: 来源: 2017-04-07 09:18:02 阅读 我要评论

'Caught an error inside the finally block.'); 
  •  
  •     } 
  •  
  •  
  • 例如:

    1. function runWithoutThrowing(func) { 
    2.  
    3.     try { 
    4.  
    5.         func(); 
    6.  
    7.     } catch (e) { 
    8.  
    9.         console.log('There was an error, but I will not throw it.'); 
    10.  
    11.         console.log('The error\'s message was: ' + e.message) 
    12.  
    13.     } 
    14.  
    15.  
    16.   
    17.  
    18. function funcThatThrowsError() { 
    19.  
    20.     throw new TypeError('I am a TypeError.'); 
    21.  
    22.  
    23.   
    24.  
    25. runWithoutThrowing(funcThatThrowsError);  

    如不雅用户传递给函数 runWithoutThrowing 的参数抛出了一个缺点对象, 膳绫擎的代码能正常捕获缺点. 然后, 如不雅是抛出一个字符串, 就会碰着一些问题了:

    在 Node 的 REPL 模式中运行上述代码会获得如下输出:

    1. function runWithoutThrowing(func) { 
    2.  
    3.     try { 
    4.  
    5.         func(); 
    6.  
    7.     } catch (e) { 
    8.  
    9.         console.log('There was an error, but I will not throw it.'); 
    10.  
    11.         console.log('The error\'s message was: ' + e.message) 
    12.  
    13.     } 
    14.  
    15.  
    16.   
    17.  
    18. function funcThatThrowsString() { 
    19.  
    20.     throw 'I am a String.'
    21.  
    22.  
    23.   
    24.  
    25. runWithoutThrowing(funcThatThrowsString);  

    如今第二个 console.log 会输出undefined. 这看起来不是很重要, 但如不雅你须要确保 Error 对象有一个特定的属性或者用另一种方法来处理 Error 对象的特定属性(例如 Chai的throws断言的做法), 你就得做大年夜量的工作来确保法度榜样的┞俘确运行.

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

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

    1. const fs = require('fs'); 
    2.  
    3.   
    4.  

        推荐阅读

        关于JavaScript的数组随机排序

      JavaScript 开辟中有时会碰到要将一个数组随机排序(shuffle)的需求,一个常见的写法是如许:function shuffle(arr) { arr.sort(function () { return Math.random() - 0.5; >>>详细阅读


      本文标题:JavaScript错误处理和堆栈追踪浅析

      地址:http://www.17bianji.com/lsqh/34615.html

    关键词: 探索发现

    乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

    网友点评
    自媒体专栏

    评论

    热度

    精彩导读
    栏目ID=71的表不存在(操作类型=0)