Skip to content

ExceptionFilter

reference
1 min readUpdated

Kind: Interface

Source: packages/common/interfaces/exceptions/exception-filter.interface.ts

Part of: Common

Interface describing implementation of an exception filter.

ExceptionFilter defines the contract for handling exceptions thrown during request processing. Implementations receive the thrown exception and an ArgumentsHost, allowing them to create framework-specific error responses, log failures, or transform errors before they reach the client.

Diagram

mermaid
graph LR
  A[Request Handler] -->|throws exception| B[ExceptionFilter.catch]
  B --> C[ArgumentsHost]
  C --> D[HTTP / RPC / WebSocket Context]
  B --> E[Formatted Error Response]
  E --> F[Client]

Usage

ts
import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
} from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter<HttpException> {
  catch(exception: HttpException, host: ArgumentsHost) {
    const response = host.switchToHttp().getResponse();
    const request = host.switchToHttp().getRequest();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      message: exception.message,
      path: request.url,
      timestamp: new Date().toISOString(),
    });
  }
}

// Register globally:
// app.useGlobalFilters(new HttpExceptionFilter());

AI Coding Instructions

  • Implement catch(exception, host) and use host.switchToHttp(), switchToRpc(), or switchToWs() for the active transport.
  • Type the exception generic, such as ExceptionFilter<HttpException>, when the filter handles a specific error class.
  • Add @Catch(ErrorType) to bind a filter to one or more exception types.
  • Avoid exposing stack traces or internal error details in production responses.
  • Register filters at the appropriate scope: method, controller, module provider, or globally with useGlobalFilters().

Used by

10 references from 10 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.

Imported by (10)

  • HttpExceptionFilterintegration/inspector/src/common/filters/http-exception.filter.ts:8
  • RequestFilterintegration/websockets/src/request.filter.ts:4
  • ApplicationConfigpackages/core/application-config.ts:13
  • BaseExceptionFilterContextpackages/core/exceptions/base-exception-filter-context.ts:11
  • BaseExceptionFilterpackages/core/exceptions/base-exception-filter.ts:17
  • NestApplicationpackages/core/nest-application.ts:54
  • DependenciesScannerpackages/core/scanner.ts:75
  • NestMicroservicepackages/microservices/nest-microservice.ts:35

…and 2 more.

Was this page helpful?

Download as PDF
ExceptionFilter — NestJS head-to-head