The ArgumentsHost class in NestJS is a special class that lets you access the arguments (parameters) of a route handler method. This includes the request, response and other contextual information.

Over my time in developing NestJS services, the ArgumentsHost class has come in handy multiple times to improve the exception handling features.

In this post, I’m going to explain how you can use the NestJS ArgumentsHost class for handling exceptions globally and perform custom actions based on the request and response objects.

1 – NestJS Custom Exception Filter with ArgumentsHost

First, make sure you have a NestJS application set up. If you are new to NestJS, you can start with my detailed post on NestJS fundamentals.

With the basic application ready, create a custom exception filter as below:

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

@Catch(HttpException)
export class CustomExceptionFilter 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();
    const message = exception.message;

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

Basically, exception filters in NestJS allow you to handle exceptions that occur during the processing of a request globally. You can read more about exceptions in my post on NestJS Exception Handling.

The CustomExceptionFilter implements the ExceptionFilter. In other words, this class implements the catch() method that gets automatic access to the exception object and an instance of the ArgumentsHost object.

Since we are dealing with HTTP requests, we can extract the HTTP-specific context from the ArgumentsHost by using the host.switchToHttp() method.

Further on, we can get the request and response objects from the context and use them to tweak our response in case of an exception. In this case, we return a JSON response with status code, timestamp, path and message.

2 – Using the NestJS Exception Handler

After defining the Exception Handler using the ArgumentsHost class, you can use it in your NestJS application.

First, you have to register the CustomExceptionFilter in the application’s app module.

import { Module } from '@nestjs/common';
import { APP_FILTER } from '@nestjs/core';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CustomExceptionFilter } from './exceptions/custom-exception.filter';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService, {
    provide: APP_FILTER,
    useClass: CustomExceptionFilter,
  },],
})
export class AppModule {}

As you can see, we use the built-in APP_FILTER token to identify the CustomExceptionFilter. The useClass properties specifies the class that should be used as the provider. In the above example, it’s the instance of the CustomExceptionFilter that will be created and used as the global exception filter.

Moving on, you can now configure a NestJS controller to use the CustomExceptionFilter as follows:

import { Controller, Get, HttpException, HttpStatus, UseFilters } from '@nestjs/common';
import { AppService } from './app.service';
import { CustomExceptionFilter } from './exceptions/custom-exception.filter';

@Controller('test')
@UseFilters(CustomExceptionFilter)
export class AppController {
  @Get()
  async getTest() {
    throw new HttpException('This is a custom exception message', HttpStatus.INTERNAL_SERVER_ERROR);
  }
}

Within the getTest() request handler, we simply throw a new HttpException. The idea is that this exception will be handled by the CustomExceptionFilter.

If you run the application now and visit http://localhost:3000/test, you should see the response as below:

{
    "statusCode": 500,
    "timestamp": "2023-10-08T01:58:09.715Z",
    "path": "/test",
    "message": "This is a custom exception message"
}

Conclusion

That’s all for this post.

In this post, we discussed how you can leverage the NestJS ArgumentsHost glass to access the arguments of a request handler. We also saw how you can practically use these arguments within a custom exception filter.

If you have any comments or queries, mention them in the comments section below.

Categories: BlogNestJS

Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *