javascript - node.js:在 bluebird 中重新抛出错误时保留堆栈跟踪

标签 javascript node.js stack-trace bluebird

我现在的情况是想重新抛出错误但保留原始错误的跟踪。在普通的旧式同步 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/

相关文章:

JavaScript 设置 JSON 数组以供稍后使用

node.js - API 命名推荐 - findById findByName

Objective-C - 命令行 (clang) - 打印堆栈跟踪

ruby-on-rails - activesupport 回调中的堆栈级别太深

node.js - 具有随机键但字符串类型的对象的 Mongoose 模式

java - 当堆栈跟踪仅显示 Eclipse 中的 native 方法时,如何找到导致错误的代码行

javascript - 为什么使用 Google Apps 脚本的日期值结果相差 1 天?

javascript - ReactJS、CSS 和 SVG 动画,以及重新渲染

javascript - 为什么 JSON.parse 会因空字符串而失败?

node.js - 使用 mongoose 时在 mongodb 中找不到 Db