Tutorial

Angular: Error Tracking Using Sentry

Published on July 4, 2017
Default avatar

By Alligator.io

Angular: Error Tracking Using Sentry

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

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);
  }
}

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

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Alligator.io

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel