我有一个名为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.js 和 caller2.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 thecheetahify
call will not be present in the stack traces
这可能是我们得到不一致结果的原因。
无论如何,恐怕您仍然需要手动记录文件名,这取决于您首先如何导入和执行它们。
关于javascript - 如何将调用者详细信息添加到 Node.js 中的错误堆栈跟踪中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45479287/