Reputation: 23
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
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
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