【发布时间】:2019-01-07 07:40:36
【问题描述】:
我想在我的代码库中记录 fileName、lineNo、ColNo。为此,我正在使用 _thisLine()。 它基本上获取行号。通过创建(不抛出)错误。 但是如果我从 promise 中调用 thisLine(),这种方法就会失败
你能帮帮我吗!
function _thisLine() {
const e = new Error();
const regex = /\((.*):(\d+):(\d+)\)$/;
const match = regex.exec(e.stack.split("\n")[2]); //i dont want to change thisLine function
return match
? {
filepath: match[1],
line: match[2],
column: match[3]
}
: "NOT FOUND";
}
function without() {
return _thisLine(); // this is ok
}
function withPromise() {
return new Promise(function(resolve, reject) {
var result = _thisLine(); //inside promise unable to capture current line number
resolve(result);
});
}
console.log("without Promise", without());
withPromise().then(function(result) {
console.log("with Promise", result);
});
我希望 withPromise 返回触发点位置 但由于承诺..我无法找到触发点
回答(我的解决方法)!对我有用!
private _thisLine() {
const e = new Error();
// for path like - 'LogWrapper.debug (D:\\Projects\\rrr\\node\\build\\server\\log_server\\log_wrapper.js:101:14)'
const regex1 = /\((.*):(\d+):(\d+)\)$/;
// for path like - 'D:\\Projects\\rrr\\node\\build\\server\\http_repo\\labtest_repo.js:58:24'
const regex2 = /(.*):(\d+):(\d+)$/;
let match = null,
callStackDepth = 2,
errorExploded = e.stack.split("\n");
while (!!!match) {
//match both kind of path patterns
match =
regex1.exec(errorExploded[callStackDepth]) ||
regex2.exec(errorExploded[callStackDepth]);
//if not found then move to nearest path
callStackDepth--;
}
return {
filepath: match[1],
line: match[2],
column: match[3]
};
}
【问题讨论】:
-
anonymous是指传递给Promise的函数,即它是一个未命名(匿名)函数 -
它仍然可以(技术上)包含该位置,不是吗?
-
@user2864740 谢谢..这让我想到..我已经更新了答案
-
@user2864740 实际上是这样,在
at new Promise上方的跟踪行中:它是文件的第 19 行第 17 列,不是吗?但是,我认为将一个堆栈帧格式化为两行是您的环境的错误。请举报。
标签: javascript typescript promise es6-promise