运行以下代码时,我会得到不同的结果,具体取决于我是否对 console.log("fnError: ", fnError)
进行了注释。这对我来说似乎很不对劲。
调用 console.log
会如何影响我的 promise ?
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 <anonymous>
// at process._tickCallback (internal/process/next_tick.js:169:7)
// ...
// caught error.message: correct message
// caught error: Error: incorrect message
// at fn (/Users/sam/dev/ethereum/pennyeth/js/temp.js:18:9)
// at <anonymous>
// at process._tickCallback (internal/process/next_tick.js:169:7)
// ...
注意正在记录“不正确的消息”。如果你注释掉 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 <anonymous>
// at process._tickCallback (internal/process/next_tick.js:169:7)
// ....
运行 Node 8.0.0
最佳答案
这是预期的行为。
记录错误(至少通过 util.inspect
或 String
)会评估其 .stack
属性。实例化错误对象时不会初始化堆栈字符串,而是延迟构建以节省内存。堆栈跟踪将包含错误消息,当您更改 .message
属性时,它会反射(reflect)或不反射(reflect)在堆栈跟踪中,具体取决于是否已经创建。
来自 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.
关于javascript - 带有 promise.catch 和 console.log 的 NodeJS 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44664596/