0
0
NestJSframework~5 mins

Catch decorator in NestJS

Choose your learning style9 modes available
Introduction

The Catch decorator helps you handle errors in your NestJS application in a clean and organized way.

When you want to catch and handle exceptions in a controller or service method.
When you want to customize error responses sent to clients.
When you want to log errors or perform actions when an error occurs.
When you want to avoid repeating try-catch blocks in many places.
When you want to create global or method-specific error handling.
Syntax
NestJS
@Catch(exceptionFilter1, exceptionFilter2, ...)
export class YourExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    // handle the exception here
  }
}

The @Catch decorator marks a class as an exception filter.

You can specify which exceptions the filter should catch by passing them as arguments.

Examples
This filter catches all exceptions because no specific exception types are passed.
NestJS
@Catch()
export class AllExceptionsFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    // handle all exceptions
  }
}
This filter catches only HttpException errors.
NestJS
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    // handle only HttpException
  }
}
This filter catches multiple specific exceptions related to database errors.
NestJS
@Catch(QueryFailedError, EntityNotFoundError)
export class DatabaseExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    // handle database related errors
  }
}
Sample Program

This example shows a simple exception filter that catches HttpException errors. It sends a JSON response with the status code, current time, request path, and error message.

NestJS
import { ExceptionFilter, Catch, ArgumentsHost, HttpException } 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();

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: exception.message || 'Error occurred',
    });
  }
}
OutputSuccess
Important Notes

Remember to bind your exception filter globally or to specific controllers to activate it.

You can create multiple filters for different error types to keep your code clean.

Summary

The Catch decorator marks a class as an error handler.

It helps catch specific or all exceptions in NestJS.

Use it to customize error responses and keep your code organized.