Custom Instrumentation for Requests Module

Learn how to manually instrument your code to use Sentry's Requests module.

As a prerequisite to setting up Requests, you’ll need to first set up performance monitoring. Once this is done, the JavaScript SDK will automatically instrument outgoing HTTP requests. If that doesn't fit your use case, you can set up using custom instrumentation.

For detailed information about which data can be set, see the Requests Module developer specifications.

Once this is done, Sentry's Angular SDK captures all unhandled exceptions and transactions.

main.ts
Copied
import {enableProdMode} from '@angular/core';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import * as Sentry from '@sentry/angular-ivy';
import {AppModule} from './app/app.module';

Sentry.init({
  dsn: 'https://examplePublicKey@o0.ingest.sentry.io/0',
  integrations: [
    // Registers and configures the Tracing integration,
    // which automatically instruments your application to monitor its
    // performance, including custom Angular routing instrumentation
    Sentry.browserTracingIntegration(),
    // Registers the Replay integration,
    // which automatically captures Session Replays
    Sentry.replayIntegration(),
  ],

  // Set tracesSampleRate to 1.0 to capture 100%
  // of transactions for performance monitoring.
  // We recommend adjusting this value in production
  tracesSampleRate: 1.0,

  // Set `tracePropagationTargets` to control for which URLs distributed tracing should be enabled
  tracePropagationTargets: ['localhost', /^https:\/\/yourserver\.io\/api/],

  // Capture Replay for 10% of all sessions,
  // plus for 100% of sessions with an error
  replaysSessionSampleRate: 0.1,
  replaysOnErrorSampleRate: 1.0,
});

platformBrowserDynamic()
  .bootstrapModule(AppModule)
  .then(success => console.log(`Bootstrap success`))
  .catch(err => console.error(err));

The Angular SDK exports a function to instantiate an ErrorHandler provider that will automatically send JavaScript errors captured by Angular's error handler.

app.module.ts
Copied
import {NgModule, ErrorHandler} from '@angular/core';
import * as Sentry from '@sentry/angular-ivy';

@NgModule({
  // ...
  providers: [
    {
      provide: ErrorHandler,
      useValue: Sentry.createErrorHandler({
        showDialog: true,
      }),
    },
  ],
  // ...
})
export class AppModule {}

You can configure the behavior of createErrorHandler. For more details see the ErrorHandlerOptions interface in our repository.

For performance monitoring, register TraceService as a provider with a Router as its dependency:

app.module.ts
Copied
import {NgModule} from '@angular/core';
import {Router} from '@angular/router';
import * as Sentry from '@sentry/angular-ivy';

@NgModule({
  // ...
  providers: [
    {
      provide: Sentry.TraceService,
      deps: [Router],
    },
  ],
  // ...
})
export class AppModule {}

Then, either require the TraceService from inside AppModule or use APP_INITIALIZER to force instantiate Tracing.

app.module.ts
Copied
@NgModule({
  // ...
})
export class AppModule {
  constructor(trace: Sentry.TraceService) {}
}

or

app.module.ts
Copied
import {APP_INITIALIZER} from '@angular/core';
@NgModule({
  // ...
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: () => () => {},
      deps: [Sentry.TraceService],
      multi: true,
    },
  ],
  // ...
})
export class AppModule {}

NOTE: Refer to HTTP Span Data Conventions for a full list of the span data attributes.

Here is an example of an instrumented function that makes HTTP requests:

Copied
async function makeRequest(method, url) {
  return await Sentry.startSpan(
    {op: 'http.client', name: `${method} ${url}`},
    async span => {
      const parsedURL = new URL(url, location.origin);

      const response = await fetch(url, {
        method,
      });

      span?.setAttribute('http.request.method', method);

      span?.setAttribute('server.address', parsedURL.hostname);
      span?.setAttribute('server.port', parsedURL.port || undefined);

      span?.setAttribute('http.response.status_code', response.status);
      span?.setAttribute(
        'http.response_content_length',
        Number(response.headers.get('content-length'))
      );

      // A good place to set other span attributes

      return response;
    }
  );
}
Help improve this content
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").