(NestJS-11) Implementing a Global Exception Filter in NestJS

Bhargava Chary
3 min read3 days ago

--

Handling exceptions effectively is a crucial part of building robust and user-friendly applications. In NestJS, we can use Exception Filters to catch and manage errors globally, ensuring that all unhandled exceptions return meaningful responses.

In this article, we will explore:

  • What are Exception Filters?
  • Why use a Global Exception Filter?
  • Implementing a Global Exception Filter in NestJS.
  • Registering the Global Exception Filter.

What are Exception Filters?

Exception filters in NestJS allow us to intercept errors that occur during request processing and handle them centrally. Instead of handling errors in every controller, we can define a single global exception filter to manage error responses uniformly.

Why Use a Global Exception Filter?

  • Centralized error handling: Avoids repetitive error-handling logic in controllers.
  • Custom error responses: Allows consistent error structures in API responses.
  • Logging and monitoring: Helps log errors for debugging and monitoring.
  • Better user experience: Ensures meaningful error messages are returned to clients.

Implementing a Global Exception Filter

Let’s create a global exception filter in NestJS using the following steps.

Step 1: Create an Exception Filter

Create a new file allexceptions.filter.ts in src/config folder and define the exception filter logic:

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

@Catch()
export class AllExceptionsFilter implements ExceptionFilter {

async catch(exception: any, host: ArgumentsHost) {
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();

if (exception?.response) {
return response.json({
statusCode: HttpStatus.INTERNAL_SERVER_ERROR,
message: exception.response?.error ?? "Internal server error",
});
}
return response.json({
statusCode: HttpStatus.BAD_REQUEST,
message: exception.message ?? "Internal server error",
});
}
}

Code Breakdown:

  • @Catch(): The @Catch() decorator makes this class an exception filter.
  • catch(exception: any, host: ArgumentsHost):
  • Extracts the Response and Request objects.
  • Returns a structured JSON response with error details.

Step 2: Registering the Exception Filter

We need to apply this filter globally so that all exceptions are handled consistently.

Approach 1: Register Globally in main.ts

Modify the main.ts file to use the filter across the entire application:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AllExceptionsFilter } from './config/all-exceptions.filter';

async function bootstrap() {
const app = await NestFactory.create(AppModule);

app.useGlobalFilters(new AllExceptionsFilter());

await app.listen(3000);
}
bootstrap();

Approach 2: Register Using APP_FILTER in a Module

Alternatively, register the filter inside a module using APP_FILTER provider:

import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { AllExceptionsFilter } from './config/allexceptions.filter';

@Module({
providers: [
{
provide: APP_FILTER,
useClass: AllExceptionsFilter,
},
],
})
export class MyConfigModule{}

Now, you can use any approach to filter out uncatched execptions in application.

Conclusion

In this article, we explored how to implement a Global Exception Filter in a NestJS application. We covered:

  • Understanding Exception Filters and their benefits.
  • Creating a custom Exception Filter to handle errors globally.
  • Registering the exception filter using useGlobalFilters() and APP_FILTER.
  • Testing and verifying error responses for different scenarios.

Using a Global Exception Filter ensures structured error handling, improves debugging, and provides a consistent API response format, making applications more robust and maintainable.

Next Steps

In our next article, we will explore Advanced Authentication in NestJS with Passport.js

GitHub Repository:
You can find the complete code for this implementation on GitHub: bhargavachary123

Support & Contribution If you liked this article, please consider supporting me through Buy Me a Coffee.

If you found this article useful, leave a clap (👏) and a comment. Happy coding! ⚔️

By implementing a global exception filter, you make your NestJS application more robust, maintainable, and user-friendly. 🚀

--

--

Bhargava Chary
Bhargava Chary

No responses yet