Track Errors In Your Ionic 2+ Apps

The Ionic 2 enables the creation of cross platform mobile applications with HTML, CSS and JavaScript(Angular). Ionic 2 was built with Angular 2. In this tutorial, we’ll logs Ionic 2 errors to the Atatus service.

Installation

  1. If you haven’t signed up Atatus yet, try out the free 14 day trial – no credit card required.
  2. Create a project for your Ionic 2 web application in Atatus.
  3. Copy and Paste the provided Atatus script in head tag of the main HTML page.
<script src="//dmc1acwvwny3.cloudfront.net/atatus.js"></script>
<script type="text/javascript"> atatus.config('YOUR_API_KEY').install(); </script>

Error Logging in Ionic 2 with ErrorHandler

ErrorHandler class provides a hook for centralized exception handling. The default implementation of ErrorHandler prints error messages to the console. This service is very simple by design. To intercept the error handling we need to write a custom handler.

Here is the structure for an ErrorHandler class in TypeScript:

class ErrorHandler {
    constructor(){}
    handleError(error: any): void
}

To intercept error handling, write a custom exception handler that sends the error to Atatus as follows

// /app/atatus.handler.ts
import { ErrorHandler } from '@angular/core';
declare var atatus: any;

class AtatusErrorHandler implements ErrorHandler {
  handleError(error:any) : void {
    if (atatus) {
      // Send the error to Atatus
      atatus.notify(error.originalError || error);
    }
  }
}

export default AtatusErrorHandler;

Now in our AppModule we have to add our AtatusErrorHandler as a provider

// /app/app.module.ts
import { ErrorHandler } from '@angular/core';
import { AppComponent } from './app.component';
import AtatusErrorHandler from './atatus.handler';

@NgModule({
    bootstrap: [AppComponent],
    declarations: [AppComponent],
    providers: [{provide: ErrorHandler, useClass: AtatusErrorHandler}]
})

export class AppModule { }

Now any exception in our application will be caught in our AtatusErrorHandler. You can test if everything was set up correctly by opening a console window and entering this:

throw new Error("Hi there, this is test error message.");

Track Ionic 2 Errors with free 14 day trial – no credit card required. Questions? - get in touch with us.

Atatus

#1 Solution for Logs, Traces & Metrics

tick-logo APM

tick-logo Kubernetes

tick-logo Logs

tick-logo Synthetics

tick-logo RUM

tick-logo Serverless

tick-logo Security

tick-logo More

Fizer Khan

Fizer Khan

Co-Founder & Architect at Atatus
Chennai