NodeJS

    Step by Step Guide to Creating an Exception Filter in NestJS


    Introduction

    You can create a custom exception filter in NestJS by extending the ExceptionFilter interface. This consists of making a class that captures and reports the application level errors.

    Create a custom exception filter file

    Create a custom-exception.filter.ts or similar new file:

    import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';import { Response } from 'express';@Catch()export class CustomExceptionFilter implements ExceptionFilter {  catch(exception: any, host: ArgumentsHost) {    const ctx = host.switchToHttp();    const response = ctx.getResponse<Response>();    const status = exception.status || 500;    response      .status(status)      .json({        statusCode: status,        message: exception.message || 'Internal server error',        timestamp: new Date().toISOString(),      });  }}
    • @Catch() : Use this decorator to indicate to NestJS that this filter captures exception.

    • catch(): exception should be processed in this method. We look the exception’s status and return an appropriate HTTP response complete with the status, message, and timestamp.

    Apply the Filter Globally or Locally

    Once your filter is set up, you can use it globally or locally.

    Globally: To add the filter onto all of your existing application, amend the main.ts file:

    import { NestFactory } from '@nestjs/core';import { AppModule } from './app.module';import { CustomExceptionFilter } from './filters/custom-exception.filter';async function bootstrap() {  const app = await NestFactory.create(AppModule);  app.useGlobalFilters(new CustomExceptionFilter());  await app.listen(3000);}bootstrap();

    Locally: If you only want to apply the filter to specific controllers or routes, you can use @UseFilters() on a controller or a method:

    import { Controller, Get, UseFilters } from '@nestjs/common';import { CustomExceptionFilter } from './filters/custom-exception.filter';@Controller('example')export class ExampleController {  @Get()  @UseFilters(CustomExceptionFilter)  findAll() {    throw new Error('Something went wrong');  }}

    Test Your Exception Filter

    At this stage it goes to testing the set up filter. Invoke an error in one of your routes and test the filter. When an error is triggered, the implemented custom exception filter will seamlessly integrate with the system and output the pre-defined response structure.

    Ready to transform your business with our technology solutions? Contact Us today to Leverage Our NodeJS Expertise.

    Share

    facebook
    LinkedIn
    Twitter
    Mail
    NodeJS

    Related Center Of Excellence