有人知道如何在Node.js中打印堆栈跟踪吗?
当前回答
@isaacs的答案是正确的,但如果你需要更具体或更清晰的错误堆栈,你可以使用这个函数:
function getCleanerStack() {
var err = new Error();
Error.captureStackTrace(err, getCleanerStack);
return err.stack;
}
这个功能的灵感直接来自控制台。NodeJS中的trace函数。
源代码:最新版本或旧版本。
其他回答
在控制台以更易读的方式打印错误的堆栈跟踪:
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)' ]
在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
获取函数调用者详细信息:
/**
* @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.
据我所知,在nodejs中打印完整的堆栈跟踪是不可能的,你可以只打印“部分”堆栈跟踪,你无法看到你从代码中的哪里来,只是异常发生的地方。这就是瑞恩·达尔在youtube视频中解释的内容。http://youtu.be/jo_B4LTHi3I为了精确,至少56:30。希望这能有所帮助
尝试错误。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中。