代码之家  ›  专栏  ›  技术社区  ›  icyrock.com

Javascript新函数堆栈跟踪行号减少2

  •  0
  • icyrock.com  · 技术社区  · 2 年前

    内代码的Javascript堆栈跟踪行号 new Function 2点前下班:

    const fn = new Function(` // line 1
      try {                   // line 2
        blah                  // line 3
      } catch(e) {            // line 4
        return e.stack        // line 5
      }                       // line 6
    `)
    
    console.log(fn())

    运行上述代码段会产生:

    anonymous@https://stacksnippets.net/js line 12 > Function:5:5
    

    应该说在哪里 Function:3:5 .在节点中运行时也是这样:

    $ cat stack-trace-line-nums.js 
    const fn = new Function(` // line 1
      try {                   // line 2
        blah                  // line 3
      } catch(e) {            // line 4
        return e.stack        // line 5
      }                       // line 6
    `)
    
    console.log(fn())
    $ node stack-trace-line-nums.js 
    ReferenceError: blah is not defined
        at eval (eval at <anonymous> (/tmp/stack-trace-line-nums.js:1:12), <anonymous>:5:5)
        ...
    

    最明显的演示方式是将所有代码放在同一行:

    const fn = new Function('try { blah } catch(e) { return e.stack }')
    
    console.log(fn())

    它产生:

    anonymous@https://stacksnippets.net/js line 12 > Function:3:7
    

    而不是 Function:1:7 .

    知道原因是什么或者有没有解决办法?

    1 回复  |  直到 2 年前
        1
  •  1
  •   CertainPerformance    2 年前

    记录函数本身,您将看到发生了什么:

    const fn = new Function(` // line 1
      try {                   // line 2
        blah                  // line 3
      } catch(e) {            // line 4
        return e.stack        // line 5
      }                       // line 6
    `)
    console.log(fn);
    console.log(fn())

    它实际上变成:

     function anonymous(
    ) {
     // line 1
      try {                   // line 2
    

    第一行是函数定义,第二行是参数列表的结尾和块的开头,只有在第3行中,传递给构造函数的函数的实际主体才会被插入。

    所以,每次只需在行号上加2。