NuGet npm Samples

Logging to elmah.io from Angular

elmah.io.javascript works great with Angular applications too. To log all errors happening in your Angular app, install elmah.io.javascript through npm as described in Logging from JavaScript.

In the same folder as the app.module.ts file add a new file named elmah-io-error-handler.ts and include the following content:

import {ErrorHandler} from '@angular/core';

import * as Elmahio from 'elmah.io.javascript';

export class ElmahIoErrorHandler implements ErrorHandler {
  logger: Elmahio;
  constructor() {
    this.logger = new Elmahio({
      apiKey: 'API_KEY',
      logId: 'LOG_ID'
    });
  }
  handleError(error) {
    if (error && error.message) {
      this.logger.error(error.message, error);
    } else {
      this.logger.error('Error in application', error);
    }
  }
}

Reference both ErrorHandler and ElmahIoErrorHandler in the app.module.ts file:

import { BrowserModule } from '@angular/platform-browser';
import {ErrorHandler, NgModule} from '@angular/core'; // ⬅️ Add ErrorHandler

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import {ElmahIoErrorHandler} from './elmah-io-error-handler'; // ⬅️ Reference ElmahIoErrorHandler

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule
  ],
  // ⬇️ Reference both handlers
  providers: [{ provide: ErrorHandler, useClass: ElmahIoErrorHandler }],
  bootstrap: [AppComponent]
})
export class AppModule { }

All errors are shipped to the handleError-function by Angular and logged to elmah.io. Check out the Elmah.Io.JavaScript.AngularAspNetCore and Elmah.Io.JavaScript.AngularWebpack samples for some real working code.

AngularJS/Angular 1

For AngularJS you need to implement the $exceptionHandler instead:

(function () {
  'use strict';
  angular.module('app').factory('$exceptionHandler', ['$log', function controller($log) {
    var logger = new Elmahio({
      apiKey: 'API_KEY',
      logId: 'LOG_ID'
    });
    return function elmahExceptionHandler(exception, cause) {
      $log.error(exception, cause);
      logger.error(exception.message, exception);
    };
  }]);
})();


This article was brought to you by the elmah.io team. elmah.io is the best error management system for .NET web applications. We monitor your website, alert you when errors start happening, and help you fix errors fast.

See how we can help you monitor your website for crashes Monitor your website