0
0
NestjsHow-ToBeginner ยท 4 min read

How to Use @UseFilters Decorator in NestJS for Exception Handling

In NestJS, use the @UseFilters decorator to apply custom exception filters that catch and handle errors gracefully. You can attach it to controllers, methods, or globally to control how exceptions are processed and responses are sent.
๐Ÿ“

Syntax

The @UseFilters decorator accepts one or more exception filter classes or instances. It can be applied at the controller or method level to catch exceptions thrown in that scope.

  • @UseFilters(FilterClass): Applies the filter to the decorated method or controller.
  • FilterClass: A class implementing ExceptionFilter interface with a catch() method.
typescript
import { UseFilters, Controller, Get } from '@nestjs/common';

@UseFilters(MyExceptionFilter)
@Controller('cats')
export class CatsController {
  @UseFilters(AnotherFilter)
  @Get()
  findAll() {
    // method logic
  }
}
๐Ÿ’ป

Example

This example shows how to create a custom exception filter and apply it using @UseFilters to handle exceptions thrown in a controller method.

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

@Catch(HttpException)
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 ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;

    response.status(status).json({
      statusCode: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      message: exception.message || 'Unexpected error',
    });
  }
}

@Controller('test')
@UseFilters(HttpExceptionFilter)
export class TestController {
  @Get()
  getError() {
    throw new HttpException('Custom error message', HttpStatus.BAD_REQUEST);
  }
}
Output
{ "statusCode": 400, "timestamp": "2024-06-01T12:00:00.000Z", "path": "/test", "message": "Custom error message" }
โš ๏ธ

Common Pitfalls

  • Not implementing the ExceptionFilter interface correctly causes the filter to not work.
  • Forgetting to apply @UseFilters decorator or applying it to the wrong scope (method vs controller) can lead to unexpected behavior.
  • Throwing exceptions that are not caught by the filter if the filter is limited to specific exception types.
  • Using global filters incorrectly without app.useGlobalFilters() when needed.
typescript
/* Wrong: Filter class missing catch method */
class BadFilter {}

/* Right: Proper filter implementation */
import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';

@Catch()
class GoodFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    // handle exception
  }
}
๐Ÿ“Š

Quick Reference

UsageDescription
@UseFilters(FilterClass)Apply filter to controller or method
@Catch(ExceptionType)Define which exceptions the filter catches
catch(exception, host)Method to handle the exception
app.useGlobalFilters(filter)Apply filter globally to all controllers
โœ…

Key Takeaways

Use @UseFilters to apply custom exception filters at controller or method level.
Create filters by implementing ExceptionFilter interface with a catch() method.
Apply @Catch decorator on filter classes to specify exception types caught.
Remember to apply filters correctly to avoid uncaught exceptions.
Global filters can be set with app.useGlobalFilters() for app-wide handling.