将异常跟踪从 angular 添加到应用洞察

时间:2020-12-24 20:20:13

标签: angular azure azure-application-insights

我正在尝试编写从 angular 到 azure 应用程序洞察力的异常。 如果我执行 JSON.stringify(error),则会记录异常。但是我不想将错误字符串化,而我们可以在不使用字符串化的情况下保存错误吗?

工作代码:

  let exception: IExceptionTelemetry = {
   exception: new Error(JSON.stringify(error)),
 };
 this.appInsights.trackException(exception);

我尝试了下面没有字符串化的编码,但它不起作用,即在 azure appInsight 中没有记录任何错误:

 let exception: IExceptionTelemetry = {
  exception: error
};
this.appInsights.trackException(exception);

 OR
let exception: IExceptionTelemetry = {
   exception: {
     name: error.name,
     message: error.message,
     stack: error.stack
  }
};
this.appInsights.trackException(exception);

我正在使用@microsoft/applicationinsights-web ~2.4.4

1 个答案:

答案 0 :(得分:0)

不适用于 App Insights,但观察您的示例,我认为您应该尝试在“异常”中再使用一个嵌套级别,如下所示:

const {message, name, stack} = error;

let exception: IExceptionTelemetry = {
  exception: {
    message: {message, name, stack},
    ...
  },
};

还想在这里强调两件事:

  1. 如果 errorError 类的实际实例(不是自定义对象),则比 JSON.stringify(error) === "{}",因为“消息”和“堆栈”不是“错误”中的可枚举字段... 因此,当您处理 Error 的字段时,您必须隐式访问它们。
  2. 在这种情况下,App Insight 将接收一个对象而不是字符串化对象。正确吗?

更新 我在文档中找到了这个:

appInsights.trackException({exception: new Error('some error')});

所以也许这会奏效:

const {message, name, stack} = error;

let exception: IExceptionTelemetry = {
  exception: new Error(message),
};