Logo

dev-resources.site

for different kinds of informations.

Global Error Handler in Angular + Application Insights

Published at
4/19/2020
Categories
angular
errors
applicationinsights
azure
Author
salimchemes
Author
11 person written this
salimchemes
open
Global Error Handler in Angular + Application Insights

We don't like errors, but they will happen anyway, so it's important to have a centralized way to handle errors in our angular app. We want to catch, identify and take actions with them.
In this post we will:

  • Implement global error handler in angular
  • Add Application Insights (aka AI) sdk
  • Track errors in AI

Implement global error handler in angular
Angular makes our life easier catching the errors globally thank to ErrorHandler class, so let's see how to implement it

  • Create Global Error Handler service and implement ErrorHandler class
import { Injectable, ErrorHandler } from "@angular/core";
import { HttpErrorResponse } from "@angular/common/http";

@Injectable({
  providedIn: "root",
})
export class GlobalErrorHandler implements ErrorHandler {
  constructor() {}

  handleError(error: Error | HttpErrorResponse) {}
}
Enter fullscreen mode Exit fullscreen mode
  • Update app.module.ts providers
import { BrowserModule } from "@angular/platform-browser";
import { NgModule, ErrorHandler } from "@angular/core"; 
import { AppRoutingModule } from "./app-routing.module";
import { AppComponent } from "./app.component";
import { HttpClientModule } from "@angular/common/http";
import { GlobalErrorHandler } from "./services/global-error-handler";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule, AppRoutingModule],
  providers: [{ provide: ErrorHandler, useClass: GlobalErrorHandler }], // Our service added

  bootstrap: [AppComponent],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Add Application Insights sdk
We need to add this dependency in our app

  • npm i --save @microsoft/applicationinsights-web

Now let's create a service to send exceptions to AI

import { Injectable } from "@angular/core";
import { ApplicationInsights } from "@microsoft/applicationinsights-web";
import { environment } from "src/environments/environment";
@Injectable({
  providedIn: "root",
})
export class ApplicationInsightService {
  appInsights: ApplicationInsights;
  constructor() {
    this.appInsights = new ApplicationInsights({
      config: {
        connectionString: environment.appInsightsConfig.connectionString, // provided by Azure
        /* ...Other Configuration Options... */
      },
    });
    this.appInsights.loadAppInsights();
    this.appInsights.trackPageView();
  }

  logError(error: Error) {
    this.appInsights.trackException({ exception: error });
  }
}

Enter fullscreen mode Exit fullscreen mode

And then integrate it with our global error handler service

import { Injectable, ErrorHandler } from "@angular/core";
import { HttpErrorResponse } from "@angular/common/http";
import { ErrorService } from "./error.service";
import { LogService } from "./log.service";

@Injectable({
  providedIn: "root",
})
export class GlobalErrorHandler implements ErrorHandler {
  constructor(
    private errorService: ErrorService,
    private logService: LogService
  ) {}

  handleError(error: Error | HttpErrorResponse) {
    if (error instanceof HttpErrorResponse) {
      // Server error
      alert(this.errorService.getHttpError(error));
    } else {
      // Client Error
      this.logService.logErrorOnApplicationInsight(error);
      alert(this.errorService.getClientSideError(error));
    }
    // Always log errors
    this.logService.logError(error);
  }
}
Enter fullscreen mode Exit fullscreen mode

logService is just a wrapper to take log actions

import { Injectable } from "@angular/core";
import { ApplicationInsightService } from "./application-insight.service";
import { HttpErrorResponse } from "@angular/common/http";

@Injectable({
  providedIn: "root"
})
export class LogService {
  constructor(private applicationInsightService: ApplicationInsightService) {}

  logErrorOnApplicationInsight(error: Error) {
    return this.applicationInsightService.logError(error);
  }

  logError(error: Error | HttpErrorResponse) {
    console.error(error);
  }
}

Enter fullscreen mode Exit fullscreen mode

Track errors in AI
To be able to see errors we send from the app we need to

  • Create AI artifact (need a resource group first)
  • Get connection string and add it into our app (you will find it in Azure portal)
  • Throw an error from our app and track exception (check example app)

Alt Text

This is how the errors look in AI
Alt Text

References

applicationinsights Article's
30 articles in total
Favicon
Optimize and Monitor Power Apps Like a Pro with Application Insights
Favicon
Application Insights - 5 Tips to Improve Your Observability
Favicon
Announcing the Tracetest Integration with Azure App Insights
Favicon
Application Insights: Display Heatmap of Page Views per calendar week
Favicon
Using Application Insights with Bicep to monitor Azure Static Web Apps and Azure Functions
Favicon
Using Application Insights For Better Application Logging
Favicon
kusto & concat string array
Favicon
Week 12 2021 - Tips I learned this week
Favicon
Application Insights for Worker Service using Serilog
Favicon
Expose data from Application Insights
Favicon
Using Fiddler for Application Insights codeless java agent with docker on WSL2
Favicon
A quick intro: Application Insights for your Angular Java stack
Favicon
Monitorando uma aplicação VueJS com o Application Insights
Favicon
Cell CMS — Criando logs robustos e monitorando uma API
Favicon
Global Error Handler in Angular + Application Insights
Favicon
Monitor application via Application Insights and send alert: Part 4 Offline Scenario?
Favicon
Monitor application via Application Insights and send alert: Part 2 Understand Telemetry Types and use advanced monitoring
Favicon
Monitor application via Application Insights and send alert: Part 1 Set Rule and Action in Unified Alert
Favicon
Web App Monitoring with Application Insights
Favicon
Application Insights SDK for Node.js part 5 : Out of box telemetries - Exception, Performance and Live Metrics Stream
Favicon
Application Insights SDK for Node.js part 4 : Out of box telemetries - Basics and Console
Favicon
Application Insights SDK for Node.js part 3 : Application Map
Favicon
Application Insights SDK for Node.js part 1 : Basic usage
Favicon
Application Insights SDK for Node.js part 2 : Track events
Favicon
Bulk add Application Insights Availability Test IPs to Azure App Service Access Restrictions using Az PowerShell
Favicon
Deploying Azure Functions with Application Insights via ARM
Favicon
Gated Release
Favicon
Adding Application Insights to Azure Functions
Favicon
What the heck is Business Intelligence?
Favicon
Monitor application via Application Insights and send alert: Part 3 Optimize telemetry and alerts

Featured ones: