What is Exception Filter in NestJS: Explanation and Example
exception filter is a class that handles errors thrown during request processing. It catches exceptions and lets you control the response sent to the client, improving error management and user experience.How It Works
Think of an exception filter in NestJS like a safety net under a tightrope walker. When an error (exception) happens while your app is running, instead of crashing or showing a confusing message, the filter catches it gracefully. It then decides what message or status code to send back to the user.
This works by implementing a special interface that listens for thrown exceptions. When an exception occurs, NestJS passes it to the filter, which can then inspect the error, log it, and customize the response. This keeps your app stable and your users informed.
Example
This example shows a simple exception filter that catches all errors and returns a JSON response with a custom message and status code.
import { ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } 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() : HttpStatus.INTERNAL_SERVER_ERROR; const message = exception instanceof HttpException ? (typeof exception.getResponse() === 'string' ? exception.getResponse() : (exception.getResponse() as any).message || 'Internal server error') : 'Internal server error'; response.status(status).json({ timestamp: new Date().toISOString(), path: request.url, error: message, }); } }
When to Use
Use exception filters in NestJS when you want to handle errors in a centralized way. They are helpful to:
- Customize error messages sent to clients
- Log errors consistently
- Convert exceptions into user-friendly responses
- Handle specific error types differently (like validation errors vs server errors)
For example, in an online store app, you might use filters to return clear messages when a product is not found or when a user sends invalid data.
Key Points
- Exception filters catch errors thrown during request handling.
- They let you customize HTTP responses for errors.
- Filters improve app stability and user experience.
- You can create global or route-specific filters.
- They help separate error handling logic from business logic.