Angular: Error Tracking Using Sentry

Sentry is a popular error tracking service that allows to track errors in your productions apps. Sentry is a paid service, but it has a generous free plan and in your app you’ll use the open source Raven-js client to interface with Sentry. Let’s go over getting up and running with Sentry for Angular 2+ apps.

Installation

It’s pretty straightforward to get started. Just install the Raven-js client using Yarn or npm:

$ npm install raven-js --save

# or with Yarn:
$ yarn add raven-js

Now setup the client in your app module:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { AppComponent } from './app.component';

import * as Raven from 'raven-js';

Raven
  .config('https://<YOUR-SENTRY-KEY>@sentry.io/<YOUR-PROJECT-ID>')
  .install();

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

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [{ provide: ErrorHandler, useClass: RavenErrorHandler }],
  bootstrap: [AppComponent]
})
export class AppModule {}

Tip: Tracking Errors in Production Only

You’ll want Sentry to track errors only in your production apps and keep the errors logged to the console when in development mode.

You can use something like the following to provide the RavenErrorHandler class as the error handler only when in production. Notice the use of environment variables here:

app.module.ts

// ...

import { environment } from '../environments/environment';
import * as Raven from 'raven-js';

Raven
  .config('https://<YOUR-SENTRY-KEY>@sentry.io/<YOUR-PROJECT-ID>')
  .install();

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

export function provideErrorHandler() {
  if (environment.production) {
    return new RavenErrorHandler();
  } else {
    return new ErrorHandler();
  }
}

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [{ provide: ErrorHandler, useFactory: provideErrorHandler }],
  bootstrap: [AppComponent]
})
export class AppModule {}

And that's it 😅. Now any unhandled error in production will be reported in your Sentry dashboard along with the stack trace. Much better than relying on your app's users to report problems!

More Usage Examples

Errors are tracked automatically, but you can go a bit further by providing user context and providing extra breadcrumbs to Sentry.

setUserContext

You can set a user context for Sentry with setUserContext. This makes it easy to know which of your users triggered the error:

// ...

import * as Raven from 'raven-js';

@Component({ ... })
export class AppComponent implements OnInit {
  ngOnInit() {
    Raven.setUserContext({
      username: 'Good Ol Paul',
      email: 'paul@alligator.io',
      id: '777'
    });
  }
}

With this, the errors will be associated to the user in question. When the user logs out, you can reset the context with a call to setUserContext with no arguments:

Raven.setUserContext()

In a real app, you'll probably want to set and unset the user context from some sort of auth service.

captureBreadcrumb

Breadcrumbs in Sentry are the series of events leading to the error. Sentry creates these breadcrumbs automatically when it can, but you can also provide them explicitly where needed:

// ...

import * as Raven from 'raven-js';

@Component({ ... })
export class AppComponent implements OnInit {
  ngOnInit() {
    Raven.captureBreadcrumb({
      category: 'Authorization',
      level: 'info',
      message: 'User tried to access restricted area',
      type: 'navigation'
    });
  }
}

captureException

captureException allows you to manually tell Sentry to capture an error. You’d use this if you don’t want to have Sentry as the global error handler for your app, and instead just want to trigger manual exception captures:

onChange(event) {
  try {
    event.target.value.map(x => {
      console.log(x * 2);
    });
  } catch (e) {
    Raven.captureException(new Error(`Oops, something went wrong: ${e}`));
  }
}

With the above, the event.target.value is a string, and the map function doesn’t exist on strings, so Sentry will capture the following error:

Oops, something went wrong: TypeError: event.target.value.map is not a function
  Tweet It
✖ Clear

🕵 Search Results

🔎 Searching...