3 回答

TA貢獻1813條經(jīng)驗 獲得超2個贊
任何Error對象都具有stack捕獲其構(gòu)造點的成員。
var stack = new Error().stack
console.log( stack )
或更簡單地說:
console.trace("Here I am!")

TA貢獻1155條經(jīng)驗 獲得超0個贊
正如已經(jīng)回答的那樣,您可以簡單地使用trace命令:
console.trace("I am here");
但是,如果您遇到有關(guān)如何記錄異常的堆棧跟蹤的問題,則只需記錄Exception對象即可。
try {
// if something unexpected
throw new Error("Something unexpected has occurred.");
} catch (e) {
console.error(e);
}
它將記錄:
錯誤:發(fā)生了意外情況。
在對象的主要位置(c:\ Users \ Me \ Documents \ MyApp \ app.js:9:15)
。(c:\ Users \ Me \ Documents \ MyApp \ app.js:17:1
)
位于Object.Module._extensions..js(module.js:478:10 )的Module._compile(module.js:460:26))
在 啟動時(node.js
)
在Function.Module.runMain(module.js:501:10)
在Function.Module._load(module.js:310:12 )在Module.load(module.js:355:32):129:16),
位于node.js:814:3
如果您的Node.js版本小于6.0.0,則僅記錄Exception對象是不夠的。在這種情況下,它將僅打印:
[錯誤:發(fā)生了意外情況。]
對于節(jié)點版本<6,使用console.error(e.stack)而不是console.error(e)打印錯誤消息以及完整的堆棧,就像當前的節(jié)點版本一樣。
注:如果該異常是因為像字符串創(chuàng)建throw "myException",它無法獲取堆棧跟蹤和記錄e.stack的產(chǎn)量不確定。
為了安全起見,您可以使用
console.error(e.stack || e

TA貢獻1891條經(jīng)驗 獲得超3個贊
要Error以更易讀的方式在控制臺中打印stacktrace :
console.log(ex, ex.stack.split("\n"));
結(jié)果示例:
[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)' ]
添加回答
舉報