Progressive Full Stack Application Development with Live Projects

Nest JS

Implementing Global Error Handler in Nest JS

In NestJS, you can implement global error handling with consistent responses by leveraging the built-in exception filters. Exception filters allow you to intercept exceptions thrown in your application and provide a custom response.

Here’s how you can implement global error handling in NestJS

Step 1: Create a Custom Exception Filter

First, create a custom exception filter to handle exceptions globally. This filter will catch all exceptions and return a consistent response format.

Create a file http-exception.filter.ts

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

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

    let statusCode = 500;
    let message = 'Internal server error';
    
    if (exception instanceof HttpException) {
      statusCode = exception.getStatus();
      message = exception.getResponse();
    }

    response.status(statusCode).json({
      statusCode,
      message: typeof message === 'string' ? message : message.message || 'Internal server error',
      path: request.url,
      timestamp: new Date().toISOString(),
    });
  }
}

				
			

Step 2: Apply the Global Exception Filter

Next, register the exception filter globally in your main app module.

In main.ts, apply the global exception 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);

  // Register the global exception filter
  app.useGlobalFilters(new HttpExceptionFilter());

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

				
			

Step 3: Customizing Error Handling (Optional)

You can further customize how different types of exceptions are handled. For example, you can add additional logic to handle HttpException, ValidationError, EntityNotFoundError, etc., in different ways.

Step 4: Handle Other Errors (Optional)

You may want to handle specific types of errors, such as database errors, by creating custom exception classes. For instance

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

export class NotFoundException extends HttpException {
  constructor(message: string) {
    super({ message, error: 'Not Found' }, HttpStatus.NOT_FOUND);
  }
}

				
			

You can then throw new NotFoundException('Resource not found') from your service or controller.

Step 5: Test the Error Handling

You can now test the error handling by causing various types of errors in your controllers or services and verifying that they return a consistent format like

				
					{
  "statusCode": 500,
  "message": "Internal server error",
  "path": "/some-path",
  "timestamp": "2025-01-17T12:00:00.000Z"
}

				
			

Conclusion

By using NestJS exception filters, you can provide consistent error responses across your application, making it easier for clients to handle errors in a uniform way.