运行以下代码时,我会得到不同的结果,具体取决于我是否注释掉了console.log(“fnError:”,fnError).这对我来说似乎很不对劲.
世界上如何调用console.log影响我的承诺?
function run() {
var fn = function(){
throw new Error("incorrect message");
};
// returns a promise that should fail with
// an error object whose .message is "correct message"
var promisifiedFn = function(){
return Promise.resolve()
.then(fn)
.catch((fnError) => {
// commenting this out fixes things! //
console.log("fnError: ",fnError);
///////////////////////////////////////
fnError.message = "correct message";
throw fnError;
})
}
promisifiedFn().catch((e) => {
console.log("caught error.message:",e.message);
console.log("caught error:",e);
});
}
run();
以上产生:
// fnError: Error: incorrect message
// at fn (/Users/sam/dev/ethereum/pennyeth/js/temp.js:18:9)
// at
注意记录“不正确的消息”.如果你注释掉console.log(“fnError:”,fnError),你会得到:
// caught error.message: correct message
// caught error: Error: correct message
// at fn (/Users/sam/dev/ethereum/pennyeth/js/temp.js:18:9)
// at
运行节点8.0.0
最佳答案
这是预期的行为.
记录错误(至少通过util.inspect或String)会评估其.stack属性.实例化错误对象时,不会初始化堆栈字符串,但是为了节省内存而延迟构建堆栈字符串.堆栈跟踪将包含错误消息,当您更改.message属性时,它将反映或不反映在堆栈跟踪中,具体取决于是否已创建.
从the V8 stack trace API description开始:
For efficiency stack traces are not formatted when they are captured but on demand,the first time the stack property is accessed.
从the official node Error
documentation开始:
The string representing the stack trace is lazily generated when the error.stack property is accessed.