有人知道如何在Node.js中打印堆栈跟踪吗?
当前回答
在v15.12.0中,有各种方法可以做到这一点,
1. console.trace(anything)
2. Error.captureStackTrace(Object)
3. console.log(new Error().stack)
4. Try Catch - Use console.log(e), where `e` is catched by catch block
或者更好地使用 在任何Javascript代码中的stacktracejs
其他回答
如果你只想记录错误的堆栈跟踪(而不是错误消息),Node 6及以上会自动在堆栈跟踪中包含错误名称和消息,如果你想做一些自定义错误处理,这有点烦人:
console.log (error.stack.replace(错误。信息,”)
这个解决方案将只记录错误名称和堆栈跟踪(因此,例如,您可以格式化错误消息,并在代码中的其他地方以您希望的方式显示它)。
上面的例子只打印错误名称,后面跟着堆栈跟踪,例如:
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)
而不是:
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)
现在主机上有一个专门的功能:
console.trace()
@isaacs的答案是正确的,但如果你需要更具体或更清晰的错误堆栈,你可以使用这个函数:
function getCleanerStack() {
var err = new Error();
Error.captureStackTrace(err, getCleanerStack);
return err.stack;
}
这个功能的灵感直接来自控制台。NodeJS中的trace函数。
源代码:最新版本或旧版本。
如上所述,您可以简单地使用trace命令:
console.trace("I am here");
但是,如果您遇到这个问题时正在搜索如何记录异常的堆栈跟踪,则可以简单地记录exception对象。
try {
// if something unexpected
throw new Error("Something unexpected has occurred.");
} catch (e) {
console.error(e);
}
它将记录:
错误:发生了意想不到的事情。 at main (c:\Users\Me\Documents\MyApp\app.js:9:15) 在对象。用户(c: \ \我的文档\ \ MyApp \ app.js: 1) 在模块。_compile (module.js 460:26): at Object.Module._extensions. js (module.js:478:10) 在模块。负载(module.js 355:32): 在Function.Module。_load (module.js 310:12): Function.Module.runMain (module.js:501:10) 在启动(node.js:129:16) 在node . js: 814:3
如果你的Node.js版本小于6.0.0,记录Exception对象是不够的。在这种情况下,它只打印:
[错误:发生了意想不到的事情。]
对于Node版本< 6,使用console.error(e.stack)而不是console.error(e)来打印错误消息加上完整的堆栈,就像当前Node版本那样。
注意:如果异常创建为像throw "myException"这样的字符串,则不可能检索堆栈跟踪并记录e.stack的结果为undefined。
为了安全起见,你可以使用
console.error(e.stack || e);
它适用于旧版本和新版本的Node.js。
获取函数调用者详细信息:
/**
* @typedef {Object} TCallerInfo
* @property {() => string} toString
* @property {string} str Caller error stack line.
* @property {string} file Caller file path.
* @property {number} line Caller line.
* @property {number} col Caller column.
* @property {Error} error Caller error stack instance.
*/
/**
* @returns {TCallerInfo | null}
*/
function getCallerLine() {
const err = new Error();
const stack = err.stack || '';
const callerLine = stack.split(/\n\s*at\s+/g);
if (callerLine.length >= 2) {
const str = callerLine[3];
const [file, line, col] = str
.replace(/^\s*at\s+/, '')
.replace(/^(.*):(\d+):(\d+)$/, '$1|$2|$3')
.split(/\|/g);
const o = {
toString: () => str,
get str() {
return str;
},
get file() {
return file;
},
get line() {
return parseInt(line);
},
get col() {
return parseInt(col);
},
get error() {
return err;
},
};
return o;
} else {
return null;
}
}
用法:
function foo() {
console.info(getCallerLine());
}
foo(); // Prints this line as Caller Line details.