Error Logging for Ionic 2 with Sentry (Raven.js)

Sentry is a realtime, platform-agnostic error logging and aggregation platform, that helps me catch errors across different projects. Raven.js is Sentry’s official browser JavaScript client and supports „quite a few“ technologies and frameworks (like plain-old JavaScript, Node.js: Express, Koa, Connect, Angular.js 1, Angular, Ember, React, Vue,…).

Ionic 2 comes with an excellent Error-Handling by default. It simply smashes all exceptions right into the developer’s face (the „React approach“ to handle things). This in itself is alright for development, but in production you should probably log all exceptions with solutions like Sentry.

To log exceptions with Sentry on Ionic 2, I decided to extend the existing IonicErrorHandler to additionally forward the logs to Sentry. The snippet below gives an example:

import * as Raven from 'raven-js';
import {NgModule, ErrorHandler} from '@angular/core';
import {IonicApp, IonicModule, IonicErrorHandler} from 'ionic-angular';
import {MyApp} from './app.component';
import {FoobarPage} from '../pages/home/home';

Raven
  .config('*YOUR DSN*')
  .install();

class RavenErrorHandler extends IonicErrorHandler implements ErrorHandler {
  handleError(err: any): void {
    super.handleError(err)
    Raven.captureException(err.originalError);
  }
}

@NgModule({
  declarations: [MyApp, FoobarPage],
  imports: [
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [MyApp, FoobarPage],
  providers: [{provide: ErrorHandler, useClass: RavenErrorHandler}]
})
export class AppModule {}