I'm new to NestJs and I created a fallback exception filter, and now I would like to know how to use it. In other words, how do I import it in my application?

Here's my fallback exception filter:

@Catch(HttpException) export class HttpExceptionFilter implements ExceptionFilter { public catch(exception: HttpException, host: ArgumentsHost): any { /* Some code here */ return response.status(statusCode).json({ status: statusCode, datetime: new Date(), createdBy: "HttpExceptionFilter", errorMessage: exception.message, }) } } 

2 Answers

You'd need to bind the filter globally to be the fallback. You can do this one of two ways

  1. With a custom provider in any module. Add this to the module's providers array
{ provide: APP_FILTER, useClass: HttpExceptionFilter } 

This will still take effect in e2e tests, as it's part of the module definition

  1. By using useGlobalFilters in your bootstrap method like so
app.useGlobalFilters(new HttpExceptionFilter()); 

This will not take effect in your e2e tests, so you'll need to bind it in those too, if you want the same functionality.

Just add this in your main.ts and it should work fine:

app.useGlobalFilters(new FallbackExceptionFilter(); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.