0
votes

I am trying to use an exception filter in my NestJS app. I followed the instructions found here to setup my global ExceptionFilter, which looks like this:

@Catch()
export class DemoExceptionFilter implements ExceptionFilter
{
    private readonly logger: Logger;

    constructor()
    {
        this.logger = new Logger(DemoExceptionFilter .name);
    }

    public catch(exception: unknown, host: ArgumentsHost): void
    {
        this.logger.log(exception);
    }
}

In my AppModule I have registered the DemoExceptionFilter this way:

@Module({
    ...
    providers: [
        ...
        {
            provide: APP_FILTER,
            useClass: DemoExceptionFilter
        }
        ...
    ]
})

When I throw an exception somewhere in my code that exception gets logged by NestJS in the console but my DemoExceptionFilter is not invoked.

I also tried

app.useGlobalFilters(new DemoExceptionFilter());

in main.ts, which also does not work.

What am I missing?

1
Where are you throwing the exception?Kim Kern
In a service constructor.Andreas

1 Answers

1
votes

In the documentation, it says where global exception filters will be applied:

Global-scoped filters are used across the whole application, for every controller and every route handler.

They are not used for the application startup. So if you want to test your exception filter, throw an error in the route handler method of a controller and call the route.