NestJS


Overview

NestJS runs on Node.js, so it uses the @understand/understand-js package directly. The setup has three parts:

  1. Initialise the SDK when the app starts.
  2. Report exceptions from a global exception filter, so every unhandled error in a controller, guard, pipe or interceptor is sent.
  3. Report crashes that happen outside a request (unhandledRejection, uncaughtException).

Requirements: Node.js 18 or later and version 1.3 or later of @understand/understand-js.

Install and Initialise

npm install @understand/understand-js

Add your input key to the environment (for example in .env):

UNDERSTAND_TOKEN=your-input-key

Initialise the SDK at the top of main.ts, before the app is created:

// src/main.ts
import { HttpAdapterHost, NestFactory } from '@nestjs/core';
import Understand from '@understand/understand-js';
import { AppModule } from './app.module';
import { UnderstandExceptionFilter } from './understand-exception.filter';

Understand.init({
  env: process.env.NODE_ENV ?? 'production',
  token: process.env.UNDERSTAND_TOKEN
});

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const { httpAdapter } = app.get(HttpAdapterHost);
  app.useGlobalFilters(new UnderstandExceptionFilter(httpAdapter));

  await app.listen(process.env.PORT ?? 3000);
}

bootstrap();

Report Exceptions with a Global Filter

Nest catches every exception thrown while handling a request and turns it into an HTTP response, so these errors never become "uncaught". A global exception filter reports them and then lets Nest build the normal response:

// src/understand-exception.filter.ts
import { ArgumentsHost, Catch, HttpException, HttpStatus } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';
import Understand from '@understand/understand-js';

@Catch()
export class UnderstandExceptionFilter extends BaseExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const status =
      exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;

    // 4xx responses (validation errors, 404s, 401s) are expected: only report server errors
    if (status >= 500) {
      const request = host.getType() === 'http' ? host.switchToHttp().getRequest() : undefined;

      Understand.logError(exception, {
        status,
        method: request?.method,
        url: request?.originalUrl ?? request?.url,
        user_id: request?.user?.id
      });
    }

    super.catch(exception, host);
  }
}

You can also register the filter as a provider, which allows dependency injection:

// src/app.module.ts
import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { UnderstandExceptionFilter } from './understand-exception.filter';

@Module({
  providers: [{ provide: APP_FILTER, useClass: UnderstandExceptionFilter }]
})
export class AppModule {}

Use one of the two registrations, not both. For GraphQL or microservice contexts, host.getType() is not 'http': report the error the same way, but don't call super.catch() there, since the base filter only builds HTTP responses.

Crashes Outside Requests

Errors in timers, event emitters, cron jobs or forgotten promises don't go through Nest's filters. catchErrors() only handles browser errors, so on Node.js add process handlers in main.ts:

// src/main.ts, after Understand.init(...)
process.on('unhandledRejection', reason => {
  Understand.logError(reason);
});

process.on('uncaughtException', error => {
  // the process is in an unknown state: report, then exit as Node.js would
  const exit = () => process.exit(1);
  Promise.resolve(Understand.logError(error)).finally(exit);
  setTimeout(exit, 2000).unref();
});

Send Nest Logger Output

To also send errors and warnings written with Nest's Logger (this.logger.error(...)), extend the console logger:

// src/understand.logger.ts
import { ConsoleLogger } from '@nestjs/common';
import Understand from '@understand/understand-js';

export class UnderstandLogger extends ConsoleLogger {
  error(message: any, ...optionalParams: any[]) {
    super.error(message, ...optionalParams);
    Understand.logMessage(String(message), 'error', { logger_context: this.context, params: optionalParams });
  }

  warn(message: any, ...optionalParams: any[]) {
    super.warn(message, ...optionalParams);
    Understand.logMessage(String(message), 'warning', { logger_context: this.context });
  }
}
// src/main.ts
const app = await NestFactory.create(AppModule, { bufferLogs: true });
app.useLogger(new UnderstandLogger());

Messages sent with level error or warning get the js_error_log tag, so they appear in Errors, grouped by their message (see Levels, Tags and the Errors View). Use this instead of patchConsoleLogs(): Nest's logger writes to stdout directly, not through console.

Handled Errors and Messages

import { Injectable, Logger } from '@nestjs/common';
import Understand from '@understand/understand-js';

@Injectable()
export class PaymentsService {
  async charge(orderId: string) {
    try {
      return await this.gateway.charge(orderId);
    } catch (error) {
      Understand.logError(error, { order_id: orderId });
      throw error;
    }
  }
}
Understand.logMessage('Payment processed', 'info', { order_id: orderId });

Request Data

The SDK keeps one global context for the whole process. In a server that handles many requests at the same time, don't set per-request values (user, request ID) with withContext(): they would be applied to events from other requests too. Pass them as metadata on each call instead, as the exception filter above does with method, url and user_id. Metadata is stored under context on the event and can be searched and filtered.

Values that are the same for the whole process, such as the app version or region, are fine in withContext() or in init({ context: { ... } }).