javascript - 如何将调用者详细信息添加到 Node.js 中的错误堆栈跟踪中?

标签 javascript error-handling promise

我有一个名为inner 的函数,它执行一系列asinc 操作:

function inner(input) {
    return step1(input)
    .then(step2)
    .then(step3)
    .catch((e) => {
        throw e
    })
}

我从内部重新抛出错误,以便我可以在调用者级别处理错误。

这是一个简单的例子:

app.get('/', function(req, res){
    inner(req)
    .then(result => {
        res.render('foo', result)
    }).catch((e) => {
        res.render('error', e);

        //eventually this would be changed to logger.error(e)
        console.log(e);
    })
})

问题是,当我记录错误时,堆栈跟踪仅显示函数内部,而不显示调用者文件。如果我想在代码中使用此函数两次并且发生错误,那么我需要知道代码的哪一部分调用了它。

如何将调用者信息添加到错误堆栈跟踪中?

最佳答案

非标准功能

Error.prototype.stack文档将其标记为非标准功能,不同平台可能有不同的行为和格式。

例如,我在 Chrome 中使用以下文件对其进行了测试:

index.html

<!doctype html>
<html>
  <head>
    <script src="inner.js"></script>
    <script src="caller1.js"></script>
    <script src="caller2.js"></script>
  </head>
  <body></body>
</html>

inner.js

function inner() {
  return new Promise((resolve, reject) => {
    reject(new Error('Oh no'))
  }).catch(e => { throw e })
}

caller1.jscaller2.js

inner().catch(e => { console.log(e.stack) })

控制台中的结果:

Error: Oh no
    at Promise (setup.js:3)
    at Promise (<anonymous>)
    at inner (setup.js:2)
    at caller1.js:1
Error: Oh no
    at Promise (setup.js:3)
    at Promise (<anonymous>)
    at inner (setup.js:2)
    at caller2.js:1

inner() 和调用者都显示在堆栈跟踪中。

解决方法

就您而言,您可以手动将其记录在调用者的 catch() 中。

如果代码在浏览器中执行,则使用document.currentScript及其 src 属性来获取文件名。

编辑:在 Node.js 中

我在 Node.js v8.1.2 中测试了它,inner() 和调用者也都显示了。

顺便说一下 document 中的一段引起了我的注意:

It is important to note that frames are only generated for JavaScript functions. If, for example, execution synchronously passes through a C++ addon function called cheetahify, which itself calls a JavaScript function, the frame representing the cheetahify call will not be present in the stack traces

这可能是我们得到不一致结果的原因。

无论如何,恐怕您仍然需要手动记录文件名,这取决于您首先如何导入和执行它们。

关于javascript - 如何将调用者详细信息添加到 Node.js 中的错误堆栈跟踪中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45479287/

相关文章:

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

javascript - 既然我们有 ES6 promise ,还有理由使用 Q 或 BlueBird 之类的 promise 库吗?

javascript - Bluebird promisifyAll 在普通情况下不起作用

flash - AS3 : ERROR 1046: Type was not found or was not a compile-time constant: Stage and TextField

javascript - 如何将元素附加到 iframe 表单?

java - gwt 专注于流程面板或任何其他面板

javascript - 我可以 _.isMatch 多个值吗?

javascript - 如何用 JavaScript 替换 HTML 文档中损坏的图像?

javascript - 如何从链式 promise 更新我的 View 模型?

javascript - 联合 JS - 如何在 shapes.devs 上应用事件