0
0
NestJSframework~5 mins

Global exception filters in NestJS

Choose your learning style9 modes available
Introduction

Global exception filters help catch and handle errors in one place for your whole NestJS app. This keeps your code clean and consistent.

You want to send the same error response format for all errors in your app.
You need to log all exceptions in a central place.
You want to handle unexpected errors gracefully without crashing the app.
You want to customize HTTP error responses globally.
You want to avoid repeating error handling code in every controller.
Syntax
NestJS
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    const status = exception instanceof HttpException
      ? exception.getStatus()
      : 500;

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: exception instanceof HttpException ? exception.getResponse() : 'Internal server error',
    });
  }
}

// To apply globally in main.ts
// app.useGlobalFilters(new AllExceptionsFilter());

The @Catch() decorator without arguments catches all exceptions.

Use app.useGlobalFilters() in your main bootstrap file to apply the filter globally.

Examples
This filter catches only HTTP exceptions, not all errors.
NestJS
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    // handle only HttpException errors
  }
}
This line applies your custom exception filter to the whole app globally.
NestJS
app.useGlobalFilters(new AllExceptionsFilter());
Sample Program

This example shows a global exception filter catching all errors. The '/error' route throws a known HTTP error, '/unknown-error' throws a normal error, and '/hello' returns a normal response. The filter sends JSON error responses for exceptions.

NestJS
import { NestFactory } from '@nestjs/core';
import { Module, Controller, Get } from '@nestjs/common';
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';
import { Request, Response } from 'express';

@Catch()
class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: unknown, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    const status = exception instanceof HttpException
      ? exception.getStatus()
      : 500;

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: exception instanceof HttpException ? exception.getResponse() : 'Internal server error',
    });
  }
}

@Controller()
class AppController {
  @Get('error')
  throwError() {
    throw new HttpException('Custom error message', 400);
  }

  @Get('unknown-error')
  throwUnknownError() {
    throw new Error('Unknown error');
  }

  @Get('hello')
  hello() {
    return 'Hello World!';
  }
}

@Module({
  controllers: [AppController],
})
class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new AllExceptionsFilter());
  await app.listen(3000);
}

bootstrap();
OutputSuccess
Important Notes

Global filters catch exceptions from all controllers and services.

Always return consistent error response shapes for better client handling.

Use instanceof HttpException to check if the error is a known HTTP error.

Summary

Global exception filters catch errors app-wide in one place.

They help send consistent error responses and improve app stability.

Apply them in main.ts using app.useGlobalFilters().