Sitelet https://docs.rollbar.com/docs/angular

Angular

Rollbar SDK for Angular 2+ | Support Level: Supported

Rollbar's JavaScript SDK reports errors from any Angular application, and a custom ErrorHandler sends the errors Angular catches to Rollbar too. This guide covers Angular 17 and later, standalone and module-based. For older versions, see the rollbar.js documentation.

Prerequisites

  • An Angular 17 or later application
  • A Node.js version your Angular CLI supports. The current Angular CLI needs Node.js 22.22.3 or later on the 22 line, 24.15.0 or later on the 24 line, or 26 and up.
  • A post_client_item access token from your project's settings

Installation

npm install rollbar

Environment files

New Angular apps have no environment files. Create them:

ng generate environments

This creates src/environments/environment.ts (used by ng build) and src/environments/environment.development.ts (used by ng serve). Put your token in both:

// src/environments/environment.ts
export const environment = {
  production: true,
  rollbarAccessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',
};
// src/environments/environment.development.ts
export const environment = {
  production: false,
  rollbarAccessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',
};

Configuration

Standalone apps

ng new has created standalone apps since Angular 17. Add Rollbar to the src/app/app.config.ts it generated, and keep the providers already there, because they differ by Angular version.

  1. Add ErrorHandler and InjectionToken to the existing @angular/core import, then add these two imports below it:
import Rollbar from 'rollbar';
import { environment } from '../environments/environment';
  1. Add this code above export const appConfig:
const rollbarConfig: Rollbar.Configuration = {
  accessToken: environment.rollbarAccessToken,
  // Leave these off when your providers include provideBrowserGlobalErrorListeners()
  // (new apps on Angular 20 and later); it already sends uncaught errors and unhandled
  // rejections to RollbarErrorHandler. Otherwise set both to true.
  captureUncaught: false,
  captureUnhandledRejections: false,
  environment: environment.production ? 'production' : 'development',
};

export const RollbarService = new InjectionToken<Rollbar>('rollbar');

export function rollbarFactory(): Rollbar {
  return new Rollbar(rollbarConfig);
}

export class RollbarErrorHandler implements ErrorHandler {
  constructor(private rollbar: Rollbar) {}

  handleError(err: any): void {
    this.rollbar.error(err.originalError || err);
    console.error(err);
  }
}
  1. Add these two entries to the end of the existing providers array:
{ provide: RollbarService, useFactory: rollbarFactory },
{
  provide: ErrorHandler,
  useFactory: (rollbar: Rollbar) => new RollbarErrorHandler(rollbar),
  deps: [RollbarService],
},

On Angular 20 and later, provideBrowserGlobalErrorListeners() in the generated providers already sends uncaught errors and unhandled rejections to RollbarErrorHandler. That is why captureUncaught and captureUnhandledRejections are off in the config above. With both on, each of those errors is reported twice. Turn both on when your providers don't include it.

Module-based apps

Apps created with ng new --standalone=false or upgraded from an older version add Rollbar to their module file instead (src/app/app.module.ts, named app-module.ts in newer versions).

  1. Add ErrorHandler, Inject, Injectable, and InjectionToken to the existing @angular/core import, then add these two imports below it:
import Rollbar from 'rollbar';
import { environment } from '../environments/environment';
  1. Add this code above @NgModule:
const rollbarConfig: Rollbar.Configuration = {
  accessToken: environment.rollbarAccessToken,
  // Leave these off when your providers include provideBrowserGlobalErrorListeners()
  // (new apps on Angular 20 and later); it already sends uncaught errors and unhandled
  // rejections to RollbarErrorHandler. Otherwise set both to true.
  captureUncaught: false,
  captureUnhandledRejections: false,
  environment: environment.production ? 'production' : 'development',
};

export const RollbarService = new InjectionToken<Rollbar>('rollbar');

export function rollbarFactory(): Rollbar {
  return new Rollbar(rollbarConfig);
}

@Injectable()
export class RollbarErrorHandler implements ErrorHandler {
  constructor(@Inject(RollbarService) private rollbar: Rollbar) {}

  handleError(err: any): void {
    this.rollbar.error(err.originalError || err);
    console.error(err);
  }
}
  1. Add these two entries to the end of the providers array in @NgModule:
{ provide: RollbarService, useFactory: rollbarFactory },
{ provide: ErrorHandler, useClass: RollbarErrorHandler },

Verify your installation

Create src/app/test-error.component.ts. In a module-based app, import RollbarService from your module file (./app.module, or ./app-module in newer versions) instead of ./app.config:

// src/app/test-error.component.ts
import { Component, Inject } from '@angular/core';
import { RollbarService } from './app.config';
import Rollbar from 'rollbar';

@Component({
  selector: 'app-test-error',
  standalone: true,
  template: `
    <div class="test-buttons">
      <h2>Test Rollbar Integration</h2>
      <button (click)="sendMessage()">Send Test Message</button>
      <button (click)="triggerError()">Trigger Test Error</button>
    </div>
  `,
})
export class TestErrorComponent {
  constructor(@Inject(RollbarService) private rollbar: Rollbar) {}

  sendMessage(): void {
    this.rollbar.info('Test message from Angular');
  }

  triggerError(): void {
    this.rollbar.info('User triggered test error');
    throw new Error('Test error from Angular');
  }
}

Then put it on the page. In a standalone app, add import { TestErrorComponent } from './test-error.component'; to src/app/app.ts (app.component.ts before Angular 20) and add TestErrorComponent to the imports array of the @Component. In a module-based app, add the same import to your module file and add TestErrorComponent to the imports array of the @NgModule. Then add <app-test-error></app-test-error> at the top of src/app/app.html (app.component.html before Angular 20).

Run ng serve, open http://localhost:4200, and click Trigger Test Error. The error appears in your Rollbar project within a few seconds.

Session Replay

Session Replay records what the user did before an error. It needs the rollbar/replay build of the SDK. In src/app/app.config.ts (or your module file), change import Rollbar from 'rollbar'; to import Rollbar from 'rollbar/replay'; and add replay to the config:

import Rollbar from 'rollbar/replay';

const rollbarConfig: Rollbar.Configuration = {
  // ...your options from above
  replay: {
    enabled: true,
    triggers: [
      {
        type: 'occurrence',
        level: ['warning', 'error', 'critical', 'info'],
        samplingRatio: 1.0,
      },
    ],
  },
};

For triggers, sampling, and privacy options, see the Session Replay documentation.

Person tracking

Attach the current user to error reports, and clear it on logout. configure merges into the existing payload and skips undefined, so pass null to clear the person. Rollbar's type definitions don't allow null yet, so strict TypeScript needs the cast.

import { Injectable, Inject } from '@angular/core';
import Rollbar from 'rollbar';
import { RollbarService } from './app.config'; // or your module file in a module-based app

@Injectable({ providedIn: 'root' })
export class AuthService {
  constructor(@Inject(RollbarService) private rollbar: Rollbar) {}

  setUser(user: any): void {
    this.rollbar.configure({
      payload: {
        person: {
          id: user.id,
          username: user.username,
          email: user.email,
        },
      },
    });
  }

  clearUser(): void {
    this.rollbar.configure({
      payload: {
        // null removes the person; undefined would be ignored
        person: null as any,
      },
    });
  }
}

HTTP interceptor

Report failed HTTP requests automatically. Create src/app/rollbar-http.interceptor.ts:

import { Injectable, Inject } from '@angular/core';
import {
  HttpInterceptor,
  HttpRequest,
  HttpHandler,
  HttpErrorResponse,
} from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
import Rollbar from 'rollbar';
import { RollbarService } from './app.config'; // or your module file in a module-based app

@Injectable()
export class RollbarHttpInterceptor implements HttpInterceptor {
  constructor(@Inject(RollbarService) private rollbar: Rollbar) {}

  intercept(req: HttpRequest<any>, next: HttpHandler) {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        this.rollbar.error('HTTP Error', {
          url: req.url,
          method: req.method,
          status: error.status,
          message: error.message,
        });
        return throwError(() => error);
      }),
    );
  }
}

Register it in the providers of src/app/app.config.ts. A standalone app needs provideHttpClient(withInterceptorsFromDi()), or Angular never runs the interceptor:

import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http';
import { RollbarHttpInterceptor } from './rollbar-http.interceptor';

// inside appConfig.providers
providers: [
  // ... other providers
  provideHttpClient(withInterceptorsFromDi()),
  { provide: HTTP_INTERCEPTORS, useClass: RollbarHttpInterceptor, multi: true },
],

If your app already calls provideHttpClient(), add withInterceptorsFromDi() to that call instead of adding a second one. In a module-based app, add the same two entries to the providers array of the @NgModule, with the same two imports at the top.

📘

For help with importing or requiring Rollbar into your project with Typescript or a version of ECMAScript (ES5/ES6/ES7/ES8/ES9), please see this document here

📘

For more information on rollbar.js, please see the docs here.


Did this page help you?