Introduction to error handling in Angular 7: Part 4 - Rollbar

Introduction

In this turorial, you will be introduced to errors tracking in Angular 7 using the errorHandler class and Rollbar.

angular-errorhandler-rollbar-img1

This is the last part of the Angular 7 error handling series, you can refer to the first part here, and the second here and the third part here.

Prerequisites

To be able to follow through in this article's demonstration you should have:

  • Node version 11.0 installed on your machine.
  • Node Package Manager version 6.7 (usually ships with Node installation).
  • Angular CLI version 7.0
  • The latest version of Angular (version 7)
1// run the command in a terminal
2    ng version

Confirm that you are using version 7, and update to 7 if you are not. Other things that will be nice-to-haves are:

  • A working knowledge of the Angular framework at a beginner level.
  • Familiarity with Angular services will be a plus but not a requirement.

In this series, you have been introduced earlier to handling client side errors and then HTTP errors gracefully in Angular 7 with tools like errorHandlers, Interceptors and even RxJS operators. In this post you will be shown how to track these errors in a remote tracking environment.

The problem

Let’s review the problems we face with testing and error tracking in production. You can skip this if you read part three.

Tracking errors

When your Angular application is running in the development server with ng serve you can easily track errors in the application. The fastest way you can do this for JavaScript errors is with the errorHandler as it was illustrated in this introductory post here. The errorHandler logs this error for you, the developer, in the browser console you test your application with. This is standard procedure for the development environment.

ErrorHandler limitations

When you build out the application in production and ship it to your users however, there is a big problem that should be obvious by now. Testing the shipped applications become an issue. If your application is in say beta stage, you might maybe send it to family and friends to use, you have to also be on those different devices to be able to spot the errors in their various browser consoles. This is of course not a scalable solution if you have many users who might not even be in the same location as you.

Leaving error reporting to users

Initially, the solution to this problem will be to build a system in such a way that your users can report errors on the application. However, this is rarely the case as users have been reported to be really impatient and this is confirmed by the statistics on the high churn rate of users with applications. The more likely situation that is more commonly seen in the place of error reporting is one-star ratings and high churn rate.

A user is more likely not to use your application and even give a bad review of it than they are to report the error experienced while using the app. This is very practical and it shows an underlying question of responsibility. The responsibility of reporting errors should not be on the user but the developer of the application.

Remote error tracking

What if there was a way you can still track errors in your application from all the users using the application in real time, remotely and in a centralized location. Thanks to advancement in code testing and monitoring services that has improved in web development over the years, you can now. There are a lot of services in the market right now that lets you do exactly that, some of which are Sentry, Rollbar, Airbrake, Raygun and a host of others.

In this article, you will be introduced to Rollbar and how it uses the Angular errorHandler class to remotely track and report errors in your Angular applications.

Introducing Rollbar

Rollbar is a software as a service product that shows you exception and crash reports in real-time in one centralized dashboard so you can track and debug bugs in record time. In your dashboard, similar errors are automatically grouped using Rollbar's fingerprinting technology to reduce noise, and all errors include detailed data to help you assess impact and assign priority.

Rollbar automatically collects all the data you need to replicate and debug an error, presented in ways optimized for debugging speed and it works with JavaScript source maps. With Telemetry, you can debug client-side JavaScript errors faster. It works like a black box recorder, but for errors.

Getting started

To get started using Rollbar, visit the website here and click the Sign Up button to create an account. You will see options to sign up with GitHub, Google account or any email account. If successfully created, you will see this welcome screen displayed..

angular-errorhandler-rollbar-img2

The next step is to click the LET'S DO IT button at the end of the page to open the new project creation page.

Creating your first project

The next page that appears on the interface will show you input elements where you can type in the name of the new project you want to create.

angular-errorhandler-rollbar-img3

I call mine ng-errors, you can call it any name of your choice. After deciding on that, click CONTINUE and proceed to the next stage of the onboarding process, which is to choose the SDK. For Angular 7, choose the Angular 2+ tab in the array of other languages and frameworks, then click CONTINUE.

The very next interface you will see is your Rollbar dashboard, which shows installation instructions along with the SDK configuration containing your unique private access token.

Using Rollbar

If you have followed this post from the start, you should have Angular 7 all setup in your machine, you have also now setup a Rollbar account and created a new project. Now download this demo project from our introductory article here. After unzipping it, open the project folder in VS Code and install Rollbar for browser use in a terminal inside the project with this command:

    npm install rollbar

This installs the Rollbar SDK into the project, making the Angular API available for use. Now you have to make changes in two files, go into the error.service.ts file and copy in the code block below:

1// src/app/error.service.ts
2    import * as Rollbar from 'rollbar';
3    import {
4    Injectable,
5    Inject,
6    InjectionToken,
7    ErrorHandler
8    } from '@angular/core';
9    const rollbarConfig = {
10    accessToken: 'COPY THIS FROM YOUR DASHBOARD',
11    captureUncaught: true,
12    captureUnhandledRejections: true,
13    };
14    export const RollbarService = new InjectionToken<Rollbar>('rollbar');
15    @Injectable()
16    export class RollbarErrorHandler implements ErrorHandler {
17    constructor(@Inject(RollbarService) private rollbar: Rollbar) {}
18    handleError(err:any) : void {
19    this.rollbar.error(err.originalError || err);
20    console.log('error occured here brooo');
21    }
22    }
23    export function rollbarFactory() {
24    return new Rollbar(rollbarConfig);
25    }

This code block comes directly from the Rollbar Angular API, you can now modify the error handler in any custom way you like so long as you do not change class names. I added a console log message just to see the number of times errors are logged. Also, if you copy the code exactly from here, you will get an invalid token error which will be fixed when you use your own unique token from your dashboard.

The next thing to do is to make sure to import and register the new error handler and the service in the app.module.ts file. Copy in the code below to do that:

1// src/app/app.module.ts
2    import { BrowserModule } from '@angular/platform-browser';
3    import { NgModule, ErrorHandler } from '@angular/core';
4    import { AppRoutingModule } from './app-routing.module';
5    import { AppComponent } from './app.component';
6    import { RollbarErrorHandler, RollbarService, rollbarFactory } from './error.service';
7    import { ErrorComponent } from './error/error.component';
8    @NgModule({
9    declarations: [
10    AppComponent,
11    ErrorComponent
12    ],
13    imports: [
14    BrowserModule,
15    AppRoutingModule
16    ],
17    providers: [
18    {
19    provide: ErrorHandler,
20    useClass: RollbarErrorHandler,
21    },
22    {
23    provide: RollbarService,
24    useFactory: rollbarFactory,
25    },
26    ],
27    bootstrap: [AppComponent]
28    })
29    export class AppModule { }

To test it, run your application in development environment:

    ng serve

This displays our application below

angular-errorhandler-rollbar-img4

To trigger an exception click the button with try catch, once you do that the app breaks. Now go to your Rollbar dashboard in your browser and you will see the error tracked in real time.

angular-errorhandler-rollbar-img5

If you click on the error, you will see a very well detailed and comprehensive analysis of the said error. With a lot of important sections including tracebacks, occurrences, number of users experiencing the error and even possible community solutions to the error, based off a wide range of data already collected on similar errors by Rollbar.

angular-errorhandler-rollbar-img6

Collaboration tool

Rollbar also provides a very significant feature that makes it seamless for you and your development team to be on top of your workflow with error tracking for your application. You can create a team, or be invited into one where you can all now get updates and email alerts on these errors as they occur and so you can work together towards fixing them.

angular-errorhandler-rollbar-img7

Numerous integrations

Rollbar also has a very seamless platform to integrate your application with your core open source development environment, be it GitHub, GitLab or Bitbucket. This way, you will not only be able to track errors, but have a straightforward way of fixing them and running tests all in a painless approach.

angular-errorhandler-rollbar-img8

Deploy tracking

Not only is Rollbar great for source control integration, it is also great for tracking your application deployment and continuous integration. There a lot of ways you can deploy your Angular application and Rollbar integrates with most of them to ensure you have a pain-free workflow, be it Heroku, or MS Build or Powershell or Circle CI.

angular-errorhandler-rollbar-img9

About security

Rollbar ensures the complete security of your application data. As part of this commitment, they have a variety of industry-standard security technologies and procedures to protect your information from unauthorized access, use, or disclosure, strongly adhering to HIPAA and ISO 27001 compliance and meet industry best practices where applicable. Learn more about the security policy and their compliance here.

Conclusion

Rollbar is one of the best error tracking services around for web applications. In addition to the well laid out documentation, it has a good number of integrations with tools you might already be using in your workflow and that makes adopting it an attractive option. Try Rollbar today!