javascript - 带有 promise.catch 和 console.log 的 NodeJS 错误?

标签 javascript node.js promise console.log

运行以下代码时,我会得到不同的结果,具体取决于我是否对 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.inspectString)会评估其 .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/

相关文章:

javascript - 上传HTML格式的图片并获取图片路径

javascript - 使用 Javascript AJAX 导入外部 HTML 内部内容而不使用 Jquery

javascript - 用变量替换对象文字的属性

php - 使 Javascript 成为一项要求

node.js - Node.js 核心中的 Promise

javascript - Nodejs 变量在 "await"之后未定义

node.js - 如何部署 Angular.js 应用程序?

javascript - Node.js:在调用resolve()之前解决了Promise?

node.js - Passport.authenticate() 使用 Promise 而不是自定义回调

javascript - 如何在 firebase 函数环境中解决 CORS?