L. Coe
L. Coe

Reputation: 23

How can I catch errors in middleware on nestjs

I am trying to catch errors with try-catch structure in middleware. I call next function in try block and if I have an error like null reference etc., I wait to catch the error in catch block. But it is not working.

export function GlobalMiddleware(req: Request, res: Response, next: NextFunction) {
 
 try {
    next();
 } catch (error) {
    console.log(error);
 }

}

Upvotes: 2

Views: 6824

Answers (2)

Noobogami
Noobogami

Reputation: 116

as this github comment maybe this work for you (it worked for me):

export function GlobalMiddleware(req: Request, res: Response, next: NextFunction) {
 
 try {
    next();
 } catch (error) {
    console.log(error);
    next(error);
 }

}

Upvotes: 0

Houssam
Houssam

Reputation: 1877

According to the documentation, catching all unhandled exceptions can be done using an exception filter.

You can learn more about how to use a global exception filter on the documentation as there is a section about it: https://docs.nestjs.com/exception-filters#catch-everything

Upvotes: 3

Related Questions