有人知道如何在Node.js中打印堆栈跟踪吗?
当前回答
在控制台以更易读的方式打印错误的堆栈跟踪:
console.log(ex, ex.stack.split("\n"));
结果示例:
[Error] [ 'Error',
' at repl:1:7',
' at REPLServer.self.eval (repl.js:110:21)',
' at Interface.<anonymous> (repl.js:239:12)',
' at Interface.EventEmitter.emit (events.js:95:17)',
' at Interface._onLine (readline.js:202:10)',
' at Interface._line (readline.js:531:8)',
' at Interface._ttyWrite (readline.js:760:14)',
' at ReadStream.onkeypress (readline.js:99:10)',
' at ReadStream.EventEmitter.emit (events.js:98:17)',
' at emitKey (readline.js:1095:12)' ]
其他回答
在控制台以更易读的方式打印错误的堆栈跟踪:
console.log(ex, ex.stack.split("\n"));
结果示例:
[Error] [ 'Error',
' at repl:1:7',
' at REPLServer.self.eval (repl.js:110:21)',
' at Interface.<anonymous> (repl.js:239:12)',
' at Interface.EventEmitter.emit (events.js:95:17)',
' at Interface._onLine (readline.js:202:10)',
' at Interface._line (readline.js:531:8)',
' at Interface._ttyWrite (readline.js:760:14)',
' at ReadStream.onkeypress (readline.js:99:10)',
' at ReadStream.EventEmitter.emit (events.js:98:17)',
' at emitKey (readline.js:1095:12)' ]
如果有人还在寻找这个像我一样,那么有一个模块,我们可以使用称为“堆栈跟踪”。它真的很受欢迎。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();
任何Error对象都有一个堆栈成员,该成员捕获了构造它的点。
var stack = new Error().stack
console.log( stack )
或者更简单地说:
console.trace("Here I am!")
现在主机上有一个专门的功能:
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。
推荐文章
- 如何写setTimeout与参数Coffeescript
- 将JavaScript字符串中的多个空格替换为单个空格
- JavaScript: override alert()
- 重置setTimeout
- 如何确保<select>表单字段被禁用时提交?
- jQuery有不聚焦的方法吗?
- 反应钩子-正确的方式清除超时和间隔
- TypeScript枚举对象数组
- 在React.js中正确的img路径
- 在React.js中更新组件onScroll的样式
- onClick ReactJS调用多个函数
- 如何在JavaScript中转义单引号(')?
- Ng-repeat结束事件
- 谷歌MAP API未捕获的类型错误:无法读取属性“offsetWidth”为空
- 模糊vs聚焦-有什么真正的区别吗?