Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJS: How to pass the error from one Error Filter to another?

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!

like image 897
karine Avatar asked Feb 16 '19 19:02

karine


2 Answers

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:

Global vs. Local

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());

Registration Order

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           
like image 56
Kim Kern Avatar answered Sep 27 '22 18:09

Kim Kern


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

like image 35
Tjeerd Avatar answered Sep 27 '22 17:09

Tjeerd