How to print a stack trace in Node.js?
有谁知道如何在Node.js中打印堆栈跟踪?
Any Error
object has a stack
member that traps the point at which it was constructed.
var stack = new Error().stack
console.log( stack )
or more simply:
console.trace("Here I am!")
现在在控制台上有一个专门的功能:
console.trace()
As already answered, you can simply use the trace command:
console.trace("I am here");
However, if you came to this question searching about how to log the stack trace of an exception , you can simply log the Exception object.
try {
// if something unexpected
throw new Error("Something unexpected has occurred.");
} catch (e) {
console.error(e);
}
It will log:
Error: Something unexpected has occurred.
at main (c:UsersMeDocumentsMyAppapp.js:9:15)
at Object. (c:UsersMeDocumentsMyAppapp.js:17:1)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
If your Node.js version is < than 6.0.0 , logging the Exception object will not be enough. In this case, it will print only:
[Error: Something unexpected has occurred.]
For Node version < 6, use console.error(e.stack)
instead of console.error(e)
to print the error message plus the full stack, like the current Node version does.
Note: if the exception is created as a string like throw "myException"
, it's not possible to retrieve the stack trace and logging e.stack
yields undefined .
To be safe, you can use
console.error(e.stack || e);
and it will work for old and new Node.js versions.
链接地址: http://www.djcxy.com/p/14468.html上一篇: 什么是堆栈跟踪,以及如何使用它来调试我的应用程序错误?
下一篇: 如何在Node.js中打印堆栈跟踪?