节点奇怪的堆栈跟踪

问题描述

如果我执行以下代码

"use strict";

const config = {};
const run = (fn,params) => fn(params);

run(
    params => {
        throw new Error("Simple test!");
    },{ config }
);

我得到以下堆栈跟踪:

Error: Simple test!
    at run.config.config (C:\test\test.js:10:9)
    at run (C:\test\test.js:6:29)
    at Object.<anonymous> (C:\test\test.js:8:1)
    at Module._compile (internal/modules/cjs/loader.js:1133:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
    at Module.load (internal/modules/cjs/loader.js:977:32)
    at Function.Module._load (internal/modules/cjs/loader.js:877:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
    at internal/main/run_main_module.js:18:47

出现 run.config.config 是正常的还是 bug?

解决方法

{config} 从原始 config 创建一个属性为 config 的对象。

堆栈似乎是:config 来自参数 {config}。所以来自 run.{config}.config 的“run”,显然显示为 run.config.config

如果 fn 较早分配(因此,当 fn 非匿名)时,堆栈跟踪是不同的。

const config = {foo: 1,bar: 2};
const run = (fn,config) => {
  fn(config);
};

const runFn = params => { 
    console.log(`current params: ${JSON.stringify(params)}`); 
    throw new Error("Caught ya'");
}

run(runFn,{config});

Nodejs 输出,带有 fn 参数作为预定义的命名函数(上面的代码段):

current params: {"config":{"foo":1,"bar":2}}
[...]\SO65523965.js:8
    throw new Error("Caught ya'");
    ^

Error: Caught ya'
    at runFn ([...]\SO65523965.js:8:11)
    at run ([...]\SO65523965.js:3:3)
    ...

带有内联 fn 参数的 Nodejs 输出:

current params: {"config":{"foo":1,"bar":2}}
[...]\SO65523965.js:8
    throw new Error("Caught ya'");
    ^

Error: Caught ya'
    at run.config.config ([...]\SO65523965.js:13:11)
    at run ([...]\SO65523965.js:3:3)
,

run.config.config 是正常的还是bug?

如果您指出 config 对象不应在堆栈跟踪中提及,因为它与错误无关,那很奇怪,另一方面,如果您想知道 {{ 1}},然后我怀疑:

感谢Shorthand property names syntax 这个:

config.config

相当于:

const a = 1,b = 2,c = 3;
const obj = {a,b,c};

以同样的方式,这个:

const a = 1,c = 3;
const obj = {a:a,b:b,c:c};

相当于:

run(params => {
        throw new Error("Simple test!");
    },{ config }
);

这可以解释 run(params => { throw new Error("Simple test!"); },{ config: config } ); 部分,第一个 config.config 似乎指代对象 config,第二个 ({ config: config }) 指代 .config提到的对象的属性名称