I am using NestJS for my application and catch all the errors in a Filter.
I have some logic where I want every specific error to be formatted and then be sent to the final ExceptionFilter
. I have the following code:
@Catch()
export class GlobalErrorFilter implements ExceptionFilter {
public catch(error: HttpException, host: ArgumentsHost) {
// do something
}
}
And also this one:
@Catch(NotFoundException)
export class NotfoundFilter implements ExceptionFilter<NotFoundException> {
public catch(error: NotFoundException, host: ArgumentsHost) {
// do something here
}
}
Is there a way that the first Filter catches the error after the first one? Thanks!
If multiple filters would match to an error, the one with the highest priority will run. There are two factors for the priority of an ExceptionFilter
:
Filters that are bound to a controller or one of its methods always have higher priority than global filters.
Controller:
// First NotfoundFilter is checked
@UseFilters(NotfoundFilter)
Global:
// Then GlobalErrorFilter is checked
app.useGlobalFilters(new GlobalErrorFilter());
The filter that is registered last will have the highest priority. So the most specific filter should be registered last:
@UseFilters(GlobalErrorFilter, NotfoundFilter)
// ^^^ 2nd ^^^ 1st
or
app.useGlobalFilters(new GlobalErrorFilter(), new NotfoundFilter());
// ^^^ 2nd ^^^ 1st
I see 2 different exceptions here with a specific type. So it should be possible (i think) that after the first filter catches the exception you could have it do something and then throw a new exception of the other type which should then be caught there. Hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With