Creating Custom Exception Filters in NestJS

@rnab
3 min readJan 26, 2025

--

NestJS is a powerful framework for building scalable server-side applications with TypeScript. One of its notable features is the robust and flexible exception handling system. While NestJS provides several built-in exceptions, there might be scenarios where you need to create custom exception filters to handle errors in a more controlled and specialized manner.

In this article, we will explore how to create custom exception filters in NestJS. We will cover the basics of exception filters, the benefits of custom filters, and a step-by-step guide to creating and implementing your own.

Understanding Exception Filters in NestJS

Exception filters in NestJS are designed to handle errors thrown by the application or route handlers in a centralized manner. By default, NestJS catches every unhandled exception and produces a standardized response. However, by using exception filters, developers can intercept exceptions and take control over the response, such as logging additional details or modifying the error response format.

Why Create Custom Exception Filters?

Custom exception filters can be beneficial for several reasons:

  1. Enhanced Error Handling: Capture specific exceptions and respond with more granular and meaningful error messages tailored to your application’s needs.
  2. Logging and Monitoring: Extend default error-handling behavior to include logging and monitoring actions.
  3. Consistent Error Responses: Ensure your application returns consistent and structured error responses across various modules.

Creating a Custom Exception Filter

To demonstrate how to create and use custom exception filters in NestJS, we’ll walk through a simple example where we create a filter to handle and log HttpException errors more effectively.

Step 1: Set Up a New NestJS Project

If you haven’t already set up a new NestJS project, you can do so by running the following commands:

npm i -g @nestjs/cli
nest new exception-filter-app
cd exception-filter-app

Step 2: Generate a Custom Exception Filter

In NestJS, you can use the CLI to easily generate a new filter:

nest g filter HttpException

This will create a new filter named http-exception.filter.ts inside the src directory.

Step 3: Implement the Custom Filter

Next, let’s implement our custom filter to handle and log HttpException errors.

Open the generated http-exception.filter.ts file and update it as follows:

import {
ExceptionFilter,
Catch,
ArgumentsHost,
HttpException,
HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';

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

const status = exception.getStatus();
const exceptionResponse = exception.getResponse();
const customResponse =
typeof exceptionResponse === 'string'
? { message: exceptionResponse }
: exceptionResponse;

const errorResponse = {
...customResponse,
timestamp: new Date().toISOString(),
path: request.url,
};

console.log(`HTTP Exception:`, errorResponse);

response.status(status).json(errorResponse);
}
}

In this filter, we define the catch method, which will be called whenever an HttpException is thrown. We capture the HTTP response and request objects to extract information such as status code, timestamp, and request path. Additionally, we log the error details to the console.

Step 4: Bind the Filter Globally

To apply this filter globally across the application, navigate to main.ts and modify it to use the new filter:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './http-exception.filter';

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

Step 5: Testing the Custom Exception Filter

You can now test the custom exception filter by creating a controller that throws an HttpException. Here is an example of how you might implement such a controller:

import { Controller, Get, HttpException, HttpStatus } from '@nestjs/common';

@Controller('error')
export class ErrorController {
@Get()
throwError() {
throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
}
}

Make sure to add this controller to your AppModule and start your application:

import { Module } from '@nestjs/common';
import { ErrorController } from './error.controller';

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

Test With an HTTP Client

You can now use an HTTP client like Postman or curl to send a GET request to http://localhost:3000/error. You should see a structured error response with a custom format, and the error details should be logged in the console.

Conclusion

Custom exception filters are a powerful feature in NestJS, providing developers with granular control over error handling, logging, and response formatting. By following this guide, you can create your own exception filters to tailor error handling to your application’s specific requires. Taking advantage of exception filters can greatly enhance the robustness and maintainability of your NestJS applications, providing a consistent handling mechanism for unexpected scenarios.

As you expand the complexity of your application, don’t hesitate to create additional filters for different exception types, thus modularizing your error-handling logic further.

--

--

@rnab
@rnab

Written by @rnab

Typescript, Devops, Kubernetes, AWS, AI/ML, Algo Trading

No responses yet