我现在的情况是想重新抛出错误但保留原始错误的跟踪。在普通的旧式同步 JavaScript 中,可以像这样完成:
try {
processThings();
} catch (e) {
const moreDetailedError = new Error("Couldn't process things due to: " + e.message);
moreDetailedError.original = e;
moreDetailedError.stack = moreDetailedError.stack + '\nCaused by:\n' + e.stack;
throw moreDetailedError;
}
function processThings() {
throw new Error('Internal error');
}
生成的堆栈跟踪将如下所示:
Error: Couldn't process things due to: Internal error
at Object.<anonymous> (test.js:8:29)
at Module._compile (module.js:570:32)
[...]
at bootstrap_node.js:509:3
Caused by:
Error: Internal error
at processThings (test.js:16:9)
at Object.<anonymous> (test.js:6:3)
at Module._compile (module.js:570:32)
[...]
at bootstrap_node.js:509:3
这正是我想要的。现在我希望能够使用 bluebird 在 promise 链延续中做同样的事情。以下是等效的基于 Promise 的代码(必须使用 BLUEBIRD_DEBUG=1
运行才能获得长堆栈跟踪):
const Promise = require('bluebird');
Promise.try(processThings).catch(e => {
const moreDetailedError = new Error("Couldn't process things due to: " + e.message);
moreDetailedError.original = e;
moreDetailedError.stack = moreDetailedError.stack + '\nCaused by:\n' + e.stack;
throw moreDetailedError;
});
function processThings() {
throw new Error('Internal error');
}
但是,bluebird 似乎吞掉了我的 Caused by
信息,只是给了我 moreDetailedError
的堆栈跟踪,而没有原始信息:
Unhandled rejection Error: Couldn't process things due to: Internal error
at Promise.try.catch.e (test.js:6:29)
at runCallback (timers.js:637:20)
[...]
at Object.<anonymous> (test.js:5:12)
From previous event:
at Object.<anonymous> (test.js:5:33)
at Module._compile (module.js:570:32)
[...]
at bootstrap_node.js:509:3
有没有办法通过 bluebird 使修改后的堆栈最终正确显示?
最佳答案
我可以通过简单地将原始错误的堆栈附加到 message
来规避这个问题。更详细的信息,而不是操纵其堆栈跟踪。这并不是我正在寻找的解决方案,但它适合我的目的。
关于javascript - node.js:在 bluebird 中重新抛出错误时保留堆栈跟踪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46091154/