首页 > 解决方案 > 为什么 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]
    };
  }

标签: javascripttypescriptpromisees6-promise

解决方案


我认为你需要修复你的正则表达式。(我不是正则表达式的专家)我猜你的正则表达式期望位置数据包含在括号“()”内,并且当它在内部触发时,因为没有返回的括号 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);
});


推荐阅读