0
0
NestJSframework~5 mins

Exception filters in NestJS

Choose your learning style9 modes available
Introduction

Exception filters help you catch and handle errors in your NestJS app in one place. They make your app respond nicely when something goes wrong.

You want to send custom error messages to users instead of default ones.
You need to log errors in a consistent way across your app.
You want to handle specific types of errors differently.
You want to keep your controller code clean by separating error handling.
You want to control the HTTP status codes sent when errors happen.
Syntax
NestJS
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } from '@nestjs/common';

@Catch(HttpException)
export class MyExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      message: exception.message,
      custom: 'This is a custom error message',
    });
  }
}

The @Catch() decorator tells NestJS which errors this filter handles.

The catch() method runs when an error happens and lets you customize the response.

Examples
This filter catches all exceptions and sends a generic 500 error message.
NestJS
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';

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

    response.status(500).json({
      statusCode: 500,
      message: 'Something went wrong',
    });
  }
}
This filter only catches 404 errors and sends a custom message.
NestJS
import { ExceptionFilter, Catch, ArgumentsHost, NotFoundException } from '@nestjs/common';

@Catch(NotFoundException)
export class NotFoundFilter implements ExceptionFilter {
  catch(exception: NotFoundException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      message: 'Resource not found',
    });
  }
}
Sample Program

This example shows a controller with a route that throws an error. The custom exception filter catches it and sends a JSON response with the error details and a timestamp.

NestJS
import { Controller, Get, UseFilters, HttpException, HttpStatus } from '@nestjs/common';
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';

@Catch(HttpException)
class CustomHttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const status = exception.getStatus();

    response.status(status).json({
      statusCode: status,
      message: exception.message || 'Default error message',
      timestamp: new Date().toISOString(),
    });
  }
}

@Controller('test')
@UseFilters(CustomHttpExceptionFilter)
export class TestController {
  @Get('error')
  throwError() {
    throw new HttpException('Custom error happened', HttpStatus.BAD_REQUEST);
  }
}
OutputSuccess
Important Notes

Exception filters only catch errors thrown inside the route handlers or services called by them.

You can create filters for specific error types or catch all errors by leaving @Catch() empty.

Use ArgumentsHost to access request and response objects to customize responses.

Summary

Exception filters help handle errors in one place and send custom responses.

Use @Catch() to specify which errors to catch.

Filters keep your code clean and improve user experience by controlling error messages.