npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@trxn/nestjs-sentry

v2.2.5

Published

Provides a service to send log to Sentry and an interceptor to catch errors.

Downloads

80

Readme

NestJs Sentry

Provides a service to send log to Sentry and an interceptor to catch errors.

Usage

Add Sentry Module to your App

@Module({
  imports: [
    SentryModule.register({
      dsn: 'https://[email protected]/1',
      debug: true,
      environment: 'production',
      release: API_VERSION ?? undefined,
      logLevel: 2,
    }),
  ],
})
export class AppModule {}

Enqueue steps (breadcrumbs) during the request life cycle

import { Controller, Get } from '@nestjs/common';
import { Public } from '@trxn/nestjs-core';
import { SentryPerRequestLogger } from '@trxn/nestjs-sentry';

@Controller(['sentry-tester'])
export class SentryTester {
  constructor(protected sentryPerRequestLogger: SentryPerRequestLogger) {}

  @Get('/sample')
  @Public()
  public async sample() {
    this.sentryPerRequestLogger.push('Calling sample method', 'debug');
    // ... More things
    this.sentryPerRequestLogger.push('Found 2 users in database', 'query');
    // ... More things
  }
}

Add the interceptor to the App

import { SentryAppInterceptorProvider } from '@trxn/nestjs-sentry';
import { RequestTimestampModule } from '@trxn/request-timestamp';

@Module({
  imports: [
    RequestTimestampModule,
    // ...
  ],
  providers: [SentryAppInterceptorProvider({})],
  exports: [],
})
export class AppModule {}

With this configuration, if an error occurred during the request, it will be sent to Sentry with the attached breadcrumbs.

RequestTimestampModule is required to enhanced error reporting. More information below.

Advanced usage

Filter errors that will be sent to Sentry

import { SentryAppInterceptorProvider } from '@polo/nestjs-sentry';

@Module({
  imports: [
    // ...
  ],
  providers: [
    SentryAppInterceptorProvider({
      filters: [
        (error) => error instanceof HttpException && error.getStatus() >= 500,
      ],
    }),
  ],
  exports: [],
})
export class AppModule {}

Use interceptor on specific controller

import { SentryInterceptor } from '@trxn/nestjs-sentry';

@Controller(['sentry-tester'])
@UseInterceptors(
  SentryInterceptor({
    filters: [
      (error) => error instanceof HttpException && error.getStatus() >= 500,
    ],
  }),
)
export class SentryTester {
  // ...
}

Send logs to Sentry outside a request context

You can use the global logger if you are not in a request context.

import { Injectable } from '@nestjs/common';
import { SentryLogger } from '@trxn/nestjs-sentry';

@Injectable()
export class OtherService {
  constructor(protected sentryLogger: SentryLogger) {}

  public method() {
    this.sentryLogger.warn('This is a warning');
  }
}

Send error manually

import { Injectable } from '@nestjs/common';
import { SentryLogger } from '@trxn/nestjs-sentry';

@Injectable()
export class OtherService {
  constructor(protected sentryPerRequestLogger: SentryPerRequestLogger) {}

  public method() {
    try {
      // ....
    } catch (error) {
      this.sentryPerRequestLogger.handleError(e);
    }
  }
}

Reporting

Global and per request

This module uses 2 scopes for reporting: global and per-request.

For better logging and breadcrumb merging, use the per-request scope.

To send logs to the global scope, use service SentryLogger.

To send logs to the per-request scope, use service SentryPerRequestLogger. Beware that all services using SentryPerRequestLogger will use the request scope:

@Injectable({ scope: Scope.REQUEST })

The interceptor SentryInterceptor uses the SentryPerRequestLogger.

Default integrations

By default, Sentry add console logs and HTTP requests as breadcrumbs (in the global scope). If an error occurs, these breadcrumbs are sent with the error (along manually added breadcrumbs).

For more information about these default integrations: https://docs.sentry.io/platforms/javascript/configuration/integrations/default/

Global breadcrumbs

These default integration are not request scoped. Therefore, we do filter breadcrumbs older than the request to separate signal from noise.

Warning

If two requests are concurrent, global breadcrumbs emitted by those requests will be mixed.

To disable global breadcrumbs from per request reporting, use this option: pushGlobalBreadcrumbsWithPerRequestBreadcrumbs.

Request age

We need to determine the age of the request in order to filter global breadcrumbs and associate them to the current request.

To determine the age of the request, we use the module RequestTimestampModule from @trxn/request-timestamp. This module adds the request timestamp in req.res.locals.timestamp.

If this module is not loaded, we assume the request is 2 seconds old. This age can be configured with this option: requestDefaultAge (in milliseconds).

Prisma middleware

This module adds a listener on Prisma queries: https://www.prisma.io/docs/concepts/components/prisma-client/middleware

As long as we cannot access the request context in this middleware, queries are pushed as breadcrumbs in the global scope. These breadcrumbs will then be filtered using the request's age mechanism.

Example

This controller:

@Controller(['sentry-tester'])
@UseInterceptors(
  SentryInterceptor({
    filters: [
      (error) => error instanceof HttpException && error.getStatus() >= 500,
    ],
  }),
)
export class SentryTester {
  constructor(
    @Inject(USER_SERVICE)
    protected userService: UserService,
    protected httpService: HttpService,
    protected sentryPerRequestLogger: SentryPerRequestLogger,
  ) {}

  @Get('/throw')
  @Public()
  public async throw() {
    this.sentryPerRequestLogger.push('Calling throw method', 'debug');

    const user = await this.userService.findFirst({
      where: {},
    });

    console.warn('This is a console.warn');

    await new Promise((r) => setTimeout(r, 1000));

    if (user) {
      this.sentryPerRequestLogger.push(
        `Found user "${user.name}" with email "${user.email}"`,
        'user',
      );
    } else {
      this.sentryPerRequestLogger.push('No user found', 'user');
    }

    await this.httpService
      .request({
        method: 'GET',
        url: 'https://dog.ceo/api/breeds/image/random',
        headers: {
          'Content-type': 'application/json;charset=utf-8',
        },
      })
      .toPromise();

    await new Promise((resolve, reject) =>
      setTimeout(() => {
        reject(new ConflictException('This is a conflict'));
      }, 1000),
    );

    return 'ended';
  }
}

Will show this in Sentry:

Sentry log sample