Search code examples
javascripttypescriptpromisees6-promise

Why javascript promises shows <anonymous> location in error logs?


I want to log the fileName, lineNo, ColNo in my codeBase. For that i am using _thisLine(). It basically fetches the line no. by creating(not throwing) an error. But this approach fails if i call thisLine() from promise

Can you please help me!

    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);
});

i expect the withPromise to return the trigger point location but due to promise .. i am unable to find trigger point

enter image description here

ANSWER (my workaround)!works for me!

  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]
    };
  }

Solution

  • Withdrawn - pending unacceptance

    Promise settlement handlers being executed with a clean stack was incorrectly interpreted as explaining why an Error object created inside such a handler would be missing call stack trace data.

    The data isn't missing.

    Logging the error in a browser. and drilling down in the console, shows the presence of entries in the new Error().stack property array.