How do you use a fallback exception filter in NestJs

756 Views Asked by At

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

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

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

app.useGlobalFilters(new FallbackExceptionFilter();