Javascript 如何在 Node.js 中打印堆栈跟踪?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2923858/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print a stack trace in Node.js?
提问by mike.toString
Does anyone know how to print a stack trace in Node.js?
有谁知道如何在 Node.js 中打印堆栈跟踪?
回答by isaacs
Any Errorobject has a stackmember that traps the point at which it was constructed.
任何Error对象都有一个stack成员来捕获它的构造点。
var stack = new Error().stack
console.log( stack )
or more simply:
或更简单地说:
console.trace("Here I am!")
回答by Mariusz Nowak
回答by Zanon
As already answered, you can simply use the tracecommand:
正如已经回答的那样,您可以简单地使用trace命令:
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.
但是,如果您遇到这个问题是为了搜索如何记录异常的堆栈跟踪,您可以简单地记录 Exception 对象。
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:\Users\Me\Documents\MyApp\app.js:9:15)
at Object. (c:\Users\Me\Documents\MyApp\app.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
错误:发生了意外。
在主要 (c:\Users\Me\Documents\MyApp\app.js:9:15)
在对象。(c:\Users\Me\Documents\MyApp\app.js:17:1)
在 Module._compile (module.js:460:26)
在 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 start (node.js) :129:16)
在 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:
如果您的 Node.js 版本 < 6.0.0,则记录 Exception 对象是不够的。在这种情况下,它只会打印:
[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.
对于 Node 版本 < 6,使用console.error(e.stack)而不是console.error(e)打印错误消息和完整堆栈,就像当前的 Node 版本一样。
Note:if the exception is created as a string like throw "myException", it's not possible to retrieve the stack trace and logging e.stackyields undefined.
注意:如果异常被创建为类似的字符串throw "myException",则无法检索堆栈跟踪并且日志记录会e.stack产生undefined。
To be safe, you can use
为了安全起见,您可以使用
console.error(e.stack || e);
and it will work for old and new Node.js versions.
它适用于新旧 Node.js 版本。
回答by ruX
To print stacktrace of Errorin console in more readable way:
要Error以更易读的方式在控制台中打印堆栈跟踪:
console.log(ex, ex.stack.split("\n"));
Example result:
结果示例:
[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)' ]
回答by Tim Boudreau
With a readily available Node module, it is possible to get full-length stack traces out of Node (albeit with a minor performance penalty): http://www.mattinsler.com/post/26396305882/announcing-longjohn-long-stack-traces-for-node-js
使用现成的 Node 模块,可以从 Node 中获取全长堆栈跟踪(尽管性能损失很小):http: //www.mattinsler.com/post/26396305882/annoucing-longjohn-long-stack -trace-for-node-js
回答by Zheeeng
Try Error.captureStackTrace(targetObject[, constructorOpt]).
尝试Error.captureStackTrace(targetObject[, constructorOpt])。
const myObj = {};
function c() {
// pass
}
function b() {
Error.captureStackTrace(myObj)
c()
}
function a() {
b()
}
a()
console.log(myObj.stack)
The function aand bare captured in error stack and stored in myObj.
函数a和b被捕获在错误堆栈中并存储在myObj.
回答by ElHacker
For what I know printing the complete stack trace in nodejs is not possible, you can just print a "partial" stack trace, you can not see from where you came from in the code, just where the Exception occur. That's what Ryan Dahl explains in this youtube video. http://youtu.be/jo_B4LTHi3Iat min 56:30 for being precise. Hope this helps
据我所知,在 nodejs 中打印完整的堆栈跟踪是不可能的,您可以只打印“部分”堆栈跟踪,您无法从代码中的位置看到异常发生的位置。这就是 Ryan Dahl 在这个 youtube 视频中解释的内容。http://youtu.be/jo_B4LTHi3I在 56:30 分钟准确。希望这可以帮助
回答by GrayedFox
If you want to only log the stack trace of the error (and not the error message) Node 6 and above automatically includes the error name and message inside the stack trace, which is a bit annoying if you want to do some custom error handling:
如果您只想记录错误的堆栈跟踪(而不是错误消息),Node 6 及更高版本会自动在堆栈跟踪中包含错误名称和消息,如果您想做一些自定义错误处理,这有点烦人:
console.log(error.stack.replace(error.message, ''))
console.log(error.stack.replace(error.message, ''))
This workaround will log only the error name and stack trace (so you can, for example, format the error message and display it how you want somewhere else in your code).
此解决方法将仅记录错误名称和堆栈跟踪(例如,您可以格式化错误消息并在代码中的其他位置显示您想要的方式)。
The above example would print only the error name follow by the stack trace, for example:
上面的示例将仅打印堆栈跟踪后面的错误名称,例如:
Error:
at /Users/cfisher/Git/squashed/execProcess.js:6:17
at ChildProcess.exithandler (child_process.js:213:5)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Socket.<anonymous> (internal/child_process.js:334:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:498:12)
Instead of:
代替:
Error: Error: Command failed: sh ./commands/getBranchCommitCount.sh HEAD
git: 'rev-lists' is not a git command. See 'git --help'.
Did you mean this?
rev-list
at /Users/cfisher/Git/squashed/execProcess.js:6:17
at ChildProcess.exithandler (child_process.js:213:5)
at emitTwo (events.js:106:13)
at ChildProcess.emit (events.js:191:7)
at maybeClose (internal/child_process.js:877:16)
at Socket.<anonymous> (internal/child_process.js:334:11)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at Pipe._handle.close [as _onclose] (net.js:498:12)
回答by Squidward Tentacles
@isaacsanswer is correct, but I have a more correct answer. This answer is inspired by the original source code of the Console class at node js (source code):
@isaacs答案是正确的,但我有一个更正确的答案。这个答案的灵感来自 node js 处 Console 类的原始源代码(源代码):
function getStack() {
var err = new Error();
Error.captureStackTrace(err, getStack);
return err.stack;
}
回答by Laszlo
In case someone is still looking for this like I was, then there is a module we can use called "stack-trace". It is really popular. NPM Link
如果有人仍然像我一样在寻找这个,那么我们可以使用一个名为“stack-trace”的模块。它真的很受欢迎。NPM 链接
Then walk through the trace.
然后遍历跟踪。
var stackTrace = require('stack-trace');
.
.
.
var trace = stackTrace.get();
trace.map(function (item){
console.log(new Date().toUTCString() + ' : ' + item.toString() );
});
Or just simply print the trace:
或者只是简单地打印跟踪:
var stackTrace = require('stack-trace');
.
.
.
var trace = stackTrace.get();
trace.toString();

