Skip to content

BaseExceptionFilter

reference
1 min readUpdated

Kind: Class

Source: packages/core/exceptions/base-exception-filter.ts

Part of: Core

BaseExceptionFilter is NestJS’s default HTTP exception handling foundation. It converts HttpException instances and compatible HTTP error objects into framework responses, while safely returning a generic 500 response and logging unexpected errors.

Implements: ExceptionFilter

Methods

MethodSignatureReturns
catchcatch(exception: T, host: ArgumentsHost)void
handleUnknownError`handleUnknownError(exception: T, host: ArgumentsHost, applicationRef: AbstractHttpAdapterHttpServer)`
isExceptionObjectisExceptionObject(err: any)err is Error
isHttpErrorisHttpError(err: any)err is { statusCode: number; message: string }

Properties

PropertyType
httpAdapterHostHttpAdapterHost

Where it refuses work

  • BaseExceptionFilter stops the work with an early return when !(exception instanceof HttpException).

Diagram

mermaid
graph LR
  A[Thrown exception] --> B[BaseExceptionFilter.catch]
  B --> C{HttpException?}
  C -->|Yes| D[Extract status and response body]
  D --> E[Send response through HTTP adapter]
  C -->|No| F[handleUnknownError]
  F --> G{HTTP-style error object?}
  G -->|Yes| H[Use statusCode and message]
  G -->|No| I[Return generic 500 response]
  H --> E
  I --> E

Usage

ts
import { ArgumentsHost, Catch } from '@nestjs/common';
import { BaseExceptionFilter } from '@nestjs/core';

@Catch()
export class AllExceptionsFilter extends BaseExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    // Add custom logging, metrics, or tracing here.
    console.error('Unhandled exception:', exception);

    // Preserve Nest's standard HTTP exception behavior.
    super.catch(exception, host);
  }
}

// Register the filter globally:
// app.useGlobalFilters(new AllExceptionsFilter());

AI Coding Instructions

  • Extend BaseExceptionFilter when adding cross-cutting exception behavior while retaining NestJS’s default HTTP response handling.
  • Always call super.catch(exception, host) unless the custom filter intentionally replaces the complete response flow.
  • Use handleUnknownError() for non-HttpException errors; it handles safe 500 responses and error logging.
  • Avoid exposing raw unknown error messages or stack traces in HTTP responses; rely on the base filter’s generic internal-error behavior.
  • Ensure custom filters are registered through app.useGlobalFilters() or the APP_FILTER provider token.

Relationships

  • IMPORTS → ArgumentsHost
  • IMPORTS → ExceptionFilter
  • IMPORTS → HttpException
  • IMPORTS → HttpServer
  • IMPORTS → HttpStatus
  • IMPORTS → Inject
  • IMPORTS → IntrinsicException
  • IMPORTS → Logger
  • IMPORTS → Optional
  • IMPORTS → isObject

Was this page helpful?

Download as PDF
BaseExceptionFilter — NestJS head-to-head