This website uses cookies to enhance the user experience

Exception Filters for Error Handling

Share:

Nest.js is a highly scalable, efficient and versatile framework for building server-side applications. It provides a level of abstraction above some common Node.js frameworks (such as Express.js and Fastify), without losing their features. Nest.js combines elements of Object Oriented Programming (OOP), Functional Programming (FP) and Functional Reactive Programming (FRP).

One of the outstanding features of Nest.js is its robust error handling mechanism. In this chapter, we will delve into how we can effectively use Nest.js Exception Filters for error handling in our applications.

Understanding Exception Filters

To begin with, an exception filter in Nest.js is a class annotated with the @Catch() decorator. Therefore, Exception filters help to handle errors gracefully in an application.

By default, Nest.js comes with an in-built exception layer that is responsible for handling all unhandled exceptions across an application. However, there may be some cases where you would like to have a customized behaviour for certain exceptions.

This is where Exception Filters comes into the picture.

The basic structure of an exception filter involves implementing the ExceptionFilter interface from @nestjs/common. The interface includes a catch() method which takes two arguments - the exception and the host (which is an argument wrapper).

The catch method is responsible for handling the exception and calling through the ArgumentsHost.

Let's implement a basic error filter for understanding. We'll create a filter to catch all errors in a Mandalorian TV show API. Here's how you would define the filter:

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

@Catch(HttpException)
export class MandalorianHttpExceptionFilter 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,
      });
  }
}

In the above code snippet, MandalorianHttpExceptionFilter is implemented from ExceptionFilter interface. The decorator @Catch(HttpException) is used above the class which tells Nest to call this filter for HttpExceptions.

The catch() method describes what our filter does when it catches HttpException. Here we are extracting the request and response object from our host and sending back a JSON response with the “statusCode”, “timestamp” and “path”.

Binding Filters

To bind a filter to a route handler, we utilize the @UseFilters() decorator. This can be bound to a specific route handler or a controller. Here's how to attach our MandalorianHttpExceptionFilter to one of the routes:

import { Controller, Get, UseFilters } from '@nestjs/common';
import { MandalorianHttpExceptionFilter } from './mandalorian-http-exception.filter';

@Controller('mandalorian')
export class MandalorianController {
  @UseFilters(new MandalorianHttpExceptionFilter())
  @Get()
  findAll() {
    throw new HttpException('Not Found', HttpStatus.NOT_FOUND);
  }
}

In the above code snippet, our MandalorianHttpExceptionFilter is bound to the findAll() route handler.

Since MandalorianHttpExceptionFilter is a class, we instantiate it using the new keyword and pass it to the @UseFilters() decorator.

Invoking the findAll() route handler will call our MandalorianHttpExceptionFilter which will handle the exception and give a response.

Conclusion

Exception filters help to handle errors and exceptions gracefully in applications built with Nest.js. By creating custom filters, you can define how exceptions are handled and construct meaningful error messages that make debugging easier.

Always remember that the error handling mechanism is an essential part of your application. A well-implemented error handler can protect your application and provide valuable insights about unexpected behaviours or failures.

Ultimately, the goal is to create a resilient and user-friendly application that handles errors and exceptions efficiently and provides meaningful feedback to the users. With the capability of Nest.js, handling errors is a piece of cake. Enjoy the power and flexibility it gives you to focus on other parts of your application.

0 Comment


Sign up or Log in to leave a comment


Recent job openings