有人知道如何在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)' ]

其他回答

任何Error对象都有一个堆栈成员,该成员捕获了构造它的点。

var stack = new Error().stack
console.log( stack )

或者更简单地说:

console.trace("Here I am!")

尝试错误。captureStackTrace (constructorOpt targetObject[])。

const myObj = {};
function c() {
  // pass
}

function b() {
    Error.captureStackTrace(myObj)
    c()
} 

function a() {
    b()
}

a()

console.log(myObj.stack)

函数a和b在错误堆栈中被捕获并存储在myObj中。

现在主机上有一个专门的功能:

console.trace()

据我所知,在nodejs中打印完整的堆栈跟踪是不可能的,你可以只打印“部分”堆栈跟踪,你无法看到你从代码中的哪里来,只是异常发生的地方。这就是瑞恩·达尔在youtube视频中解释的内容。http://youtu.be/jo_B4LTHi3I为了精确,至少56:30。希望这能有所帮助

在控制台以更易读的方式打印错误的堆栈跟踪:

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)' ]