Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application Insights does not track unhandled browser exceptions in Angular app

I'm experiencing an issue with the Microsoft Application Insights SDK for JavaScript that was closed/fixed awhile ago: https://github.com/Microsoft/ApplicationInsights-JS/issues/282

I created a brand new Angular app using the Angular CLI. Then I made these changes, following this article.

Added a monitoring service:

import {Injectable} from '@angular/core';
import {AppInsights} from 'applicationinsights-js';

@Injectable()
export class MonitoringService {
  private config: Microsoft.ApplicationInsights.IConfig = {
    instrumentationKey: 'KEY_GOES_HERE',
    enableDebug: true,
    verboseLogging: true
  };

  constructor() {
    if (!AppInsights.config) {
      AppInsights.downloadAndSetup(this.config);
    }
  }

  logPageView(name?: string, url?: string, properties?: any, measurements?: any, duration?: number) {
    AppInsights.trackPageView(name, url, properties, measurements, duration);
  }

  logEvent(name: string, properties?: any, measurements?: any) {
    AppInsights.trackEvent(name, properties, measurements);
  }

  trackException(exception: Error) {
    AppInsights.trackException(exception);
  }
}

Added it to my app.component.ts:

import {Component, OnInit} from '@angular/core';
import {MonitoringService} from './monitoring.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [MonitoringService]
})
export class AppComponent implements OnInit {
  title = 'app works!';

  constructor(private monitoringService: MonitoringService) { }

  ngOnInit() {
      this.monitoringService.logPageView();
  }

  throwAnException() {
      this.monitoringService.trackException(new Error('manually track exception'));
      throw 'this should appear in app insights'; // but it doesn't
  }
}

Made a simple button for throwing the exception in my app.component.html:

<h1>
  {{title}}
</h1>
<div (click)="throwAnException()">Click to throw an exception</div>

Logging a page view works, as does tracking the exception by explicitly calling trackException. From reading the documentation and various articles, I was under the impression that uncaught exceptions would always automatically get sent to Application Insights. However, I am not seeing any of those show up in the portal.

What could I be missing here?

Using these versions:

applicationinsights-js: 1.0.11
@types/applicationinsights-js: 1.0.4
like image 295
chinaowl Avatar asked Aug 22 '17 22:08

chinaowl


People also ask

How do I see exceptions in application insights?

Diagnose exceptions using Visual StudioOpen the Application Insights Search telemetry window in Visual Studio. While debugging, select the Application Insights dropdown. Select an exception report to show its stack trace. To open the relevant code file, select a line reference in the stack trace.

How do I enable insights for web app?

Select File | New Project. Select Visual C# | . NET Core | ASP.NET Core Web Application, ensure to mark the checkbox Add Application Insights to Project. Click Ok on the next screen.

Are application insights deprecated?

Because the workspace-based Application Insights enhances your monitoring experience, we retire the classic Application Insights on 29 February 2024.


1 Answers

I've struggles with the same thing and here is the things you need to know to hack it through:

What is happenning?

Angular catches all the exceptions (swallows them!) and just logs them inside console. I have not seen this behavior being explicitly told in any documentation, but I've tested this in code, so trust me. On the other hand only uncaught exceptions are autocollected! (see here). For collecting caught exceptions ( as is mostly the case when using angular framework) you have to call trackException() explicitly in your code.

How to solve it :

We will implement a service (called MonitoringService in code below) to communicate with azure application insights. Then we will tell angular to use this service to log exceptions in azure ai, instead of logging just into browser console, by extending ErrorHandler class.

1) implement MonitoringService:

We'll be using a service named MonitoringService to communicate with azure application insights. Implement that service like this:

import { Injectable } from "@angular/core";
import { ApplicationInsights } from "@microsoft/applicationinsights-web";
import { environment } from "@env/environment";

@Injectable({
  providedIn: "root",
})
export class MonitoringService {
  private appInsights: ApplicationInsights;
  constructor() {}
  startMonitoring(): void {
    this.appInsights = new ApplicationInsights({
      config: {
        instrumentationKey: environment.appInsights.instrumentationKey,
      },
    });
    this.appInsights.loadAppInsights();
    this.appInsights.trackPageView();
  }  

  logException(exception: Error, severityLevel?: number) {
    this.appInsights.trackException({
      exception: exception,
      severityLevel: severityLevel,
    });
  }
}

startMonitoring() should be called on app start up.

2) start monitoring on app start up:

Angular projects mostly have a app.component.ts file which belongs to the root module and is bootstrapped/initialized as the first component. By the term "on app start up", I actually mean the time this component is being initialized.
We'll create an instance of MonitoringService and have it start its job:

import { Component } from '@angular/core';
import { MonitoringService } from 'services/monitoring.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {
  constructor(
    private monitoringService: MonitoringService
  ) {
    this.monitoringService.startMonitoring();
  }
}

3) Log errors into application insights, before they are swallowed by framework:

Extend ErrorHandler class in your project. This class is actually a hook for centralized exception handling in angular spa. Use this hook, to log exceptions before they are swallowed by framework:

import { Injectable, ErrorHandler } from '@angular/core';
import { MonitoringService } from './monitoring.service';

@Injectable({
  providedIn: 'root'
})
export class GlobalErrorHandlerService implements ErrorHandler {

  constructor(private monitoringService: MonitoringService) { }
  handleError(error: any): void {
    console.error(error);
    this.monitoringService.logException(error);
  }
}

4) Register the ErrorHandler with Angular:

In the AppModule make sure to register this Handler with Angular:

@NgModule({
  providers: [{provide: ErrorHandler, useClass: GlobalErrorHandlerService}]
})
class AppModule {}
like image 165
Shahryar Saljoughi Avatar answered Oct 18 '22 04:10

Shahryar Saljoughi