如何在Node.js中打印堆栈跟踪?

有谁知道如何在Node.js中打印堆栈跟踪?



RISEBY
浏览 1038回答 3
3回答

慕姐8265434

任何Error对象都具有stack捕获其构造点的成员。var stack = new Error().stackconsole.log( stack )或更简单地说:console.trace("Here I am!")

白衣非少年

正如已经回答的那样,您可以简单地使用trace命令:console.trace("I am here");但是,如果您遇到有关如何记录异常的堆栈跟踪的问题,则只需记录Exception对象即可。try {&nbsp;&nbsp;&nbsp; // if something unexpected&nbsp; throw new Error("Something unexpected has occurred.");&nbsp; &nbsp; &nbsp;} catch (e) {&nbsp; console.error(e);}它将记录:错误:发生了意外情况。&nbsp; &nbsp; 在对象的主要位置(c:\ Users \ Me \ Documents \ MyApp \ app.js:9:15)&nbsp; &nbsp; 。(c:\ Users \ Me \ Documents \ MyApp \ app.js:17:1&nbsp; &nbsp; )&nbsp; &nbsp; 位于Object.Module._extensions..js(module.js:478:10 )的Module._compile(module.js:460:26))&nbsp; &nbsp; 在&nbsp; &nbsp; &nbsp;启动时(node.js&nbsp; &nbsp; )&nbsp; &nbsp; 在Function.Module.runMain(module.js:501:10)在Function.Module._load(module.js:310:12 )在Module.load(module.js:355:32):129:16),&nbsp; &nbsp; 位于node.js:814:3如果您的Node.js版本小于6.0.0,则仅记录Exception对象是不够的。在这种情况下,它将仅打印:[错误:发生了意外情况。]对于节点版本<6,使用console.error(e.stack)而不是console.error(e)打印错误消息以及完整的堆栈,就像当前的节点版本一样。注:如果该异常是因为像字符串创建throw "myException",它无法获取堆栈跟踪和记录e.stack的产量不确定。为了安全起见,您可以使用console.error(e.stack || e

万千封印

要Error以更易读的方式在控制台中打印stacktrace :console.log(ex, ex.stack.split("\n"));结果示例:[Error] [ 'Error',&nbsp; '&nbsp; &nbsp; at repl:1:7',&nbsp; '&nbsp; &nbsp; at REPLServer.self.eval (repl.js:110:21)',&nbsp; '&nbsp; &nbsp; at Interface.<anonymous> (repl.js:239:12)',&nbsp; '&nbsp; &nbsp; at Interface.EventEmitter.emit (events.js:95:17)',&nbsp; '&nbsp; &nbsp; at Interface._onLine (readline.js:202:10)',&nbsp; '&nbsp; &nbsp; at Interface._line (readline.js:531:8)',&nbsp; '&nbsp; &nbsp; at Interface._ttyWrite (readline.js:760:14)',&nbsp; '&nbsp; &nbsp; at ReadStream.onkeypress (readline.js:99:10)',&nbsp; '&nbsp; &nbsp; at ReadStream.EventEmitter.emit (events.js:98:17)',&nbsp; '&nbsp; &nbsp; at emitKey (readline.js:1095:12)' ]
打开App,查看更多内容
随时随地看视频慕课网APP