What is @sentry/angular?
@sentry/angular is a package that provides error tracking and performance monitoring for Angular applications. It helps developers capture and report errors, track performance issues, and gain insights into the health of their applications.
What are @sentry/angular's main functionalities?
Error Tracking
This feature allows you to capture and report errors in your Angular application. By initializing Sentry with your DSN and implementing a custom ErrorHandler, you can automatically send error reports to Sentry.
import * as Sentry from '@sentry/angular';
import { ErrorHandler } from '@angular/core';
Sentry.init({
dsn: 'your-dsn-url',
});
export class SentryErrorHandler implements ErrorHandler {
handleError(error) {
Sentry.captureException(error);
throw error;
}
}
Performance Monitoring
This feature allows you to monitor the performance of your Angular application. By configuring Sentry with the BrowserTracing integration and setting a sample rate, you can track performance metrics and identify bottlenecks.
import * as Sentry from '@sentry/angular';
Sentry.init({
dsn: 'your-dsn-url',
integrations: [
new Sentry.BrowserTracing({
tracingOrigins: ['localhost', 'https://yourserver.io'],
routingInstrumentation: Sentry.routingInstrumentation,
}),
],
tracesSampleRate: 1.0,
});
User Feedback
This feature allows you to collect user feedback when an error occurs. By calling the showReportDialog method with the event ID, you can prompt users to provide additional information about the error.
import * as Sentry from '@sentry/angular';
Sentry.init({
dsn: 'your-dsn-url',
});
function captureUserFeedback(eventId) {
Sentry.showReportDialog({
eventId: eventId,
});
}
Other packages similar to @sentry/angular
bugsnag-js
Bugsnag provides error monitoring and crash reporting for JavaScript applications. It offers similar functionalities to @sentry/angular, such as error tracking and performance monitoring, but also includes features like session tracking and release tracking.
rollbar
Rollbar is another error tracking and monitoring service for JavaScript applications. It provides real-time error reporting, similar to @sentry/angular, and includes additional features like telemetry, which captures events leading up to an error, and deployment tracking.
airbrake-js
Airbrake offers error monitoring and performance tracking for JavaScript applications. It provides similar functionalities to @sentry/angular, such as error tracking and performance monitoring, but also includes features like error grouping and detailed error reports.
Official Sentry SDK for Angular
Links
General
This package is a wrapper around @sentry/browser
, with added functionality related to Angular. All methods available
in @sentry/browser
can be imported from @sentry/angular
.
To use this SDK, call Sentry.init(options)
before you bootstrap your Angular application.
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { init } from '@sentry/angular';
import { AppModule } from './app/app.module';
init({
dsn: '__DSN__',
});
enableProdMode();
platformBrowserDynamic()
.bootstrapModule(AppModule)
.then(success => console.log(`Bootstrap success`))
.catch(err => console.error(err));
ErrorHandler
@sentry/angular
exports a function to instantiate ErrorHandler provider that will automatically send Javascript errors
captured by the Angular's error handler.
import { NgModule, ErrorHandler } from '@angular/core';
import { createErrorHandler } from '@sentry/angular';
@NgModule({
providers: [
{
provide: ErrorHandler,
useValue: createErrorHandler({
showDialog: true,
}),
},
],
})
export class AppModule {}
Additionally, createErrorHandler
accepts a set of options that allows you to configure its behaviour. For more details
see ErrorHandlerOptions
interface in src/errorhandler.ts
.
Tracing
@sentry/angular
exports a Trace Service, Directive and Decorators that leverage the @sentry/tracing
Tracing
integration to add Angular related spans to transactions. If the Tracing integration is not enabled, this functionality
will not work. The service itself tracks route changes and durations, where directive and decorators are tracking
components initializations.
Install
Registering a Trace Service is a 3 steps process.
- Register and configure
@sentry/tracing
BrowserTracing
integration, including custom Angular routing
instrumentation:
import { init, routingInstrumentation } from '@sentry/angular';
import { Integrations as TracingIntegrations } from '@sentry/tracing';
init({
dsn: '__DSN__',
integrations: [
new TracingIntegrations.BrowserTracing({
tracingOrigins: ['localhost', 'https://yourserver.io/api'],
routingInstrumentation: routingInstrumentation,
}),
],
tracesSampleRate: 1,
});
- Register
SentryTrace
as a provider in Angular's DI system, with a Router
as its dependency:
import { NgModule } from '@angular/core';
import { Router } from '@angular/router';
import { TraceService } from '@sentry/angular';
@NgModule({
providers: [
{
provide: TraceService,
deps: [Router],
},
],
})
export class AppModule {}
- Either require the
TraceService
from inside AppModule
or use APP_INITIALIZER
to force instantiate Tracing.
@NgModule({
})
export class AppModule {
constructor(trace: TraceService) {}
}
or
import { APP_INITIALIZER } from '@angular/core';
@NgModule({
providers: [
{
provide: APP_INITIALIZER,
useFactory: () => () => {},
deps: [TraceService],
multi: true,
},
],
})
export class AppModule {}
Use
To track Angular components as part of your transactions, you have 3 options.
TraceDirective: used to track a duration between OnInit
and AfterViewInit
lifecycle hooks in template:
import { TraceDirective } from '@sentry/angular';
@NgModule({
declarations: [TraceDirective],
})
export class AppModule {}
Then inside your components template (keep in mind that directive name attribute is required):
<app-header [trace]="'header'"></app-header>
<articles-list [trace]="'articles-list'"></articles-list>
<app-footer [trace]="'footer'"></app-footer>
TraceClassDecorator: used to track a duration between OnInit
and AfterViewInit
lifecycle hooks in components:
import { Component } from '@angular/core';
import { TraceClassDecorator } from '@sentry/angular';
@Component({
selector: 'layout-header',
templateUrl: './header.component.html',
})
@TraceClassDecorator()
export class HeaderComponent {
}
TraceMethodDecorator: used to track a specific lifecycle hooks as point-in-time spans in components:
import { Component, OnInit } from '@angular/core';
import { TraceMethodDecorator } from '@sentry/angular';
@Component({
selector: 'app-footer',
templateUrl: './footer.component.html',
})
export class FooterComponent implements OnInit {
@TraceMethodDecorator()
ngOnInit() {}
}
You can also add your own custom spans by attaching them to the current active transaction using getActiveTransaction
helper. For example, if you'd like to track the duration of Angular boostraping process, you can do it as follows:
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { init, getActiveTransaction } from '@sentry/angular';
import { AppModule } from './app/app.module';
const activeTransaction = getActiveTransaction();
const boostrapSpan =
activeTransaction &&
activeTransaction.startChild({
description: 'platform-browser-dynamic',
op: 'angular.bootstrap',
});
platformBrowserDynamic()
.bootstrapModule(AppModule)
.then(() => console.log(`Bootstrap success`))
.catch(err => console.error(err));
.finally(() => {
if (bootstrapSpan) {
boostrapSpan.finish();
}
})