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.
Exception filters in 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.
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', }); } }
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', }); } }
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.
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); } }
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.
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.