【问题标题】:Programmatic Access to TypeScript Call Stack以编程方式访问 TypeScript 调用堆栈
【发布时间】:2020-07-16 11:10:24
【问题描述】:

我正在使用 TypeScript 调试工具,遇到了我似乎无法以编程方式访问 TypeScript 调用堆栈的问题。

当我这样做时:

   const error = new Error();
   console.log(error.stack);

我得到了预期的结果,可以看到 TypeScript 调用堆栈。

但如果我这样做:

   const error = new Error();
   const errorStack = error.stack;
   console.log(errorStack);

我只得到 JavaScript 堆栈而不是预期的 TypeScript 堆栈。

问题在于如何或何时应用源映射。

有没有办法将我在第一个示例中作为控制台输出获得的相同信息获取到 TypeScript/JavaScript 变量中?非常感谢任何帮助!

【问题讨论】:

  • 您能发布您看到的两个调用堆栈的示例吗?由于您的代码是有效的 javascript,因此与 vanila javascript 相比,行为应该没有区别。你可以在this typescript playground看到这个。
  • @CameronLittle TypeScript 游乐场似乎没有使用源映射,因此您将始终看到 JavaScript 调用堆栈,而不是 TypeScript 调用堆栈。请参阅下面的后续帖子,其中包含在 Chrome 中重现该问题的示例。

标签: typescript console.log callstack


【解决方案1】:

这里有一些信息可以重现问题!

首先创建一个包含以下内容的文件“logger.ts”:

class DebugLogging {
  public log(msg: string) {
    const error = new Error();
    console.log(error.stack);

    const errorStack = error.stack;
    console.log(errorStack);

    const realStringStack = "-> " + error.stack;
    console.log(realStringStack);

    debugger

    console.log(msg);
  }
}

const logger = new DebugLogging();
logger.log("test");

然后编译 TypeScript 文件:

tsc --source-map logger.ts

现在,创建一个包含以下内容的文件“logger.html”:

<html>
  <head>
    <script src="logger.js"></script>
  </head>
  <body>
    <p>look at the console output...</p>
  <body>
</html>

在 Chrome 浏览器中打开 HTML 文件(我使用的是 V80.0.3987.163)并查看 JavaScript 控制台,它应该已经停止了“调试器”语句。

前两个 console.log 语句的输出都按预期显示相同的 TypeScript 调用堆栈。但是第三个 console.log 的输出显示的是 JavaScript 调用堆栈。

调用栈一转换成字符串,映射信息就丢失了。

您现在可以在控制台中进行实验,这样可以获得预期的结果:

> error // display the contents of the Error object
< Error
    at DebugLogging.log (logger.ts:3)
    at logger.ts:16

现在有点奇怪:通过在控制台中输入这个,您将获得 JavaScript 调用堆栈而不是 TypeScript 调用堆栈作为字符串:

> error.stack // display the contents of the Error object's stack property
< "Error
    at DebugLogging.log (file:///home/me/exer/tss/logger.js:5:21)
    at file:///home/me/exer/tss/logger.js:15:8"

> error.stack.split(/at /) // display the contents of the Error object's stack property split into parts
< (3) ["Error↵    ", "DebugLogging.log 
         (file:///Users/shunyam/exer/tss/logger.js:5:21)↵    ", 
         "file:///Users/shunyam/exer/tss/logger.js:17:8"]

现在,回到我最初的问题。如何将 TypeScript 调用堆栈的内容放入变量中以实际操作它?

感谢您的宝贵时间!

【讨论】:

    猜你喜欢
    • 2010-09-06
    • 1970-01-01
    • 2010-12-13
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-12
    相关资源
    最近更新 更多