In NestJS, exception filters are used to catch exceptions thrown in controllers and handle them to respond to the client. NestJS enables developers to create multiple exception filters and define their execution order. To pass an exception from one exception filter to another, re-throw the exception in the first filter. Exception filters can re-throw exceptions by extending the BaseExceptionFilter class and invoking the super.catch() method, enabling subsequent filters to catch and handle the exception. The following is an example of how to implement exception passing between filters:
typescriptimport { ExceptionFilter, Catch, ArgumentsHost, HttpException, } from '@nestjs/common'; import { BaseExceptionFilter } from '@nestjs/core'; // Custom first exception filter @Catch(HttpException) export class FirstExceptionFilter extends BaseExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { // Perform specific exception handling logic here // Re-throw the exception to be caught by the next exception filter super.catch(exception, host); } } // Custom second exception filter @Catch(HttpException) export class SecondExceptionFilter extends BaseExceptionFilter { catch(exception: HttpException, host: ArgumentsHost) { // Since it executes after FirstExceptionFilter, it can perform additional logic // Or alternatively, end the response with a custom response } }
To ensure the first filter passes the exception to the second filter, register these filters in the module configuration in the specified order. This is typically done in your main module or root module (AppModule):
typescriptimport { Module } from '@nestjs/common'; import { APP_FILTER } from '@nestjs/core'; @Module({ // ... providers: [ { provide: APP_FILTER, useClass: FirstExceptionFilter, }, { provide: APP_FILTER, useClass: SecondExceptionFilter, }, ], }), export class AppModule {}
In the module configuration above, note that each filter is registered using the APP_FILTER token, and NestJS determines the call order based on their position in the array. The first filter FirstExceptionFilter will first catch and handle the exception, then pass it to SecondExceptionFilter via super.catch().
Note that this approach is only applicable to exceptions of the same type. If you have multiple filters handling different exception types and wish them to execute in sequence, you may need to design a more complex logic for exception passing. Typically, if such a complex exception handling chain is necessary, reconsider whether your exception handling strategy is appropriate or if it can be achieved with simpler and more direct methods.