您好,欢迎来到12图资源库!分享精神,快乐你我!我们只是素材的搬运工!!
  • 首 页
  • 当前位置:首页 > 开发 > WEB开发 >
    深入理解JavaScript错误和堆栈追踪(5)
    时间:2017-04-25 15:33 来源:网络整理 作者:网络 浏览:收藏 挑错 推荐 打印

        // Here we will store the current stack trace into myObj 

        // This time we will hide all the frames after `b` and `b` itself 

        Error.captureStackTrace(myObj, b); 

     

    function c() { 

        d(); 

     

    function b() { 

        c(); 

     

    function a() { 

        b(); 

     

    // First we will call these functions 

    a(); 

     

    // Now let's see what is the stack trace stored into myObj.stack 

    console.log(myObj.stack); 

     

    // This will print the following stack to the console: 

    //    at a (repl:2:1) <-- As you can see here we only get frames before `b` was called 

    //    at repl:1:1 <-- Node internals below this line 

    //    at realRunInThisContextScript (vm.js:22:35) 

    //    at sigintHandlersWrap (vm.js:98:12) 

    //    at ContextifyScript.Script.runInThisContext (vm.js:24:12) 

    //    at REPLServer.defaultEval (repl.js:313:29) 

    //    at bound (domain.js:280:14) 

    //    at REPLServer.runBound [as eval] (domain.js:293:12) 

    //    at REPLServer.onLine (repl.js:513:10) 

    //    at emitOne (events.js:101:20) 

    当把b传给Error.captureStackTraceFunction时,它隐藏了b本身以及它之后所有的调用帧。因此控制台仅仅打印出一个a。

    至此你应该会问自己:“这到底有什么用?”。这非常有用,因为你可以用它来隐藏与用户无关的内部实现细节。在Chai中,我们使用它来避免向用户显示我们是如何实施检查和断言本身的不相关的细节。

    操作堆栈追踪实战

    正如我在上一节中提到的,Chai使用堆栈操作技术使堆栈跟踪更加与我们的用户相关。下面将揭晓我们是如何做到的。

    首先,让我们来看看当断言失败时抛出的AssertionError的构造函数:

    // `ssfi` stands for "start stack function". It is the reference to the 

    // starting point for removing irrelevant frames from the stack trace 

    function AssertionError (message, _props, ssf) { 

      var extend = exclude('name''message''stack''constructor''toJSON'

        , props = extend(_props || {}); 

     

      // Default values 

      this.message = message || 'Unspecified AssertionError'

      this.showDiff = false

     

      // Copy from properties 

      for (var key in props) { 

        this[key] = props[key]; 

      } 

     

      // Here is what is relevant for us: 

    (责任编辑:admin)