我想要重新抛出错误但保留原始错误的跟踪。在普通的旧同步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_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
有没有办法让蓝鸟在最后通过正确的方式获得修改后的堆栈?
答案 0 :(得分:0)
我能够通过简单地将原始错误的堆栈附加到更详细的错误的[[[Ljava.lang.String;@2a3046da, [[Ljava.lang.String;@2a098129, [[Ljava.lang.String;@198e2867, [[Ljava.lang.String;@12f40c25, [[Ljava.lang.String;@3ada9e37]
来解决问题,而不是操纵其堆栈跟踪。不是我想要的解决方案,但它适用于我的目的。