javascript - 为什么 javascript 承诺显示错误日志中的位置?
问题描述
我想在我的代码库中记录 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]
};
}
解决方案
我认为你需要修复你的正则表达式。(我不是正则表达式的专家)我猜你的正则表达式期望位置数据包含在括号“()”内,并且当它在内部触发时,因为没有返回的括号 e.stack.split("\n")[2]
,执行正则表达式返回 null。
我添加了一些 console.log 来打印出值
function _thisLine() {
const e = new Error();
const regex = /\((.*):(\d+):(\d+)\)$/;
const match = regex.exec(e.stack.split("\n")[2]);
console.log('trigger location...'+e.stack.split("\n")[2]);
console.log('match...'+match);
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
console.log('result is ...' + result);
resolve(result);
});
}
console.log("without Promise", without());
withPromise().then(function(result) {
console.log("with Promise", result);
});
推荐阅读
- export-to-csv - Powershell 中对多个 CSV 文件的单个查询结果
- c# - 以 Unity (2D) 的速度将对象移动到某个位置
- pointers - 依赖共享邮件服务器发送邮件的 VPS 上的 rDNS
- grafana - 在 grafana 中设置警报 | 百分位数与百分比
- c# - GetRequiredService 和 AddHttpClient 冻结 .NET 控制台应用程序(堆栈溢出)
- typescript - K6 测试执行行为
- python - 如何应用用户特定列表?
- r - 计算 shapefile 中每个多边形之间的最大/(或最小)距离
- php - PHPWord:是否可以用图像替换文档中的占位符文本(在文本所在的相同位置)?
- java - JPAQuery.fetchResults() 已弃用,我应该如何替换它?