有人知道如何在Node.js中打印堆栈跟踪吗?
当前回答
您可以使用node-stack-trace模块,这是一个强大的完整模块来跟踪调用堆栈。
其他回答
如果你只想记录错误的堆栈跟踪(而不是错误消息),Node 6及以上会自动在堆栈跟踪中包含错误名称和消息,如果你想做一些自定义错误处理,这有点烦人:
console.log (error.stack.replace(错误。信息,”)
这个解决方案将只记录错误名称和堆栈跟踪(因此,例如,您可以格式化错误消息,并在代码中的其他地方以您希望的方式显示它)。
上面的例子只打印错误名称,后面跟着堆栈跟踪,例如:
Error:
at /Users/cfisher/Git/squashed/execProcess.js:6:17
at ChildProcess.exithandler (child_process.js:213:5)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Socket.<anonymous> (internal/child_process.js:334:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:498:12)
而不是:
Error: Error: Command failed: sh ./commands/getBranchCommitCount.sh HEAD
git: 'rev-lists' is not a git command. See 'git --help'.
Did you mean this?
rev-list
at /Users/cfisher/Git/squashed/execProcess.js:6:17
at ChildProcess.exithandler (child_process.js:213:5)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Socket.<anonymous> (internal/child_process.js:334:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:498:12)
现在主机上有一个专门的功能:
console.trace()
如上所述,您可以简单地使用trace命令:
console.trace("I am here");
但是,如果您遇到这个问题时正在搜索如何记录异常的堆栈跟踪,则可以简单地记录exception对象。
try {
// if something unexpected
throw new Error("Something unexpected has occurred.");
} catch (e) {
console.error(e);
}
它将记录:
错误:发生了意想不到的事情。 at main (c:\Users\Me\Documents\MyApp\app.js:9:15) 在对象。用户(c: \ \我的文档\ \ MyApp \ app.js: 1) 在模块。_compile (module.js 460:26): at Object.Module._extensions. js (module.js:478:10) 在模块。负载(module.js 355:32): 在Function.Module。_load (module.js 310:12): Function.Module.runMain (module.js:501:10) 在启动(node.js:129:16) 在node . js: 814:3
如果你的Node.js版本小于6.0.0,记录Exception对象是不够的。在这种情况下,它只打印:
[错误:发生了意想不到的事情。]
对于Node版本< 6,使用console.error(e.stack)而不是console.error(e)来打印错误消息加上完整的堆栈,就像当前Node版本那样。
注意:如果异常创建为像throw "myException"这样的字符串,则不可能检索堆栈跟踪并记录e.stack的结果为undefined。
为了安全起见,你可以使用
console.error(e.stack || e);
它适用于旧版本和新版本的Node.js。
如果有人还在寻找这个像我一样,那么有一个模块,我们可以使用称为“堆栈跟踪”。它真的很受欢迎。NPM链接
然后穿过痕迹。
var stackTrace = require('stack-trace');
.
.
.
var trace = stackTrace.get();
trace.map(function (item){
console.log(new Date().toUTCString() + ' : ' + item.toString() );
});
或者只是简单地打印跟踪:
var stackTrace = require('stack-trace');
.
.
.
var trace = stackTrace.get();
trace.toString();
您可以使用node-stack-trace模块,这是一个强大的完整模块来跟踪调用堆栈。
推荐文章
- 窗口。亲近与自我。close不关闭Chrome中的窗口
- 同步和异步编程(在node.js中)的区别是什么?
- 在d3.js中调整窗口大小时调整svg的大小
- 如何编辑通过npm安装的节点模块?
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?