0
I write an application with Express and Typescript, and to capture the exceptions of the routes I do so:
index ts.
// ...
app.use(userRoutes);
app.use(handleError);
// ...
having 'handleError' in a separate file:
export function handleError(
err: Error,
req: Request,
res: Response,
next: NextFunction
) {
return res.status(500).json(err);
}
so far so good, but errors coming from asynchronous functions there is a solution to create a package on top of the controller function on the route:
// ...
router.get("/users", wrapAsync(getUsers));
router.get("/users/:id", wrapAsync(getUser));
router.post("/users", wrapAsync(createUser));
// ...
export function wrapAsync(fn: RequestHandler) {
return function (req: Request, res: Response, next: NextFunction) {
fn(req, res, next).catch(next);
};
}
The question is: I’ll have to wrap up all the controller methods to generally capture your asynchronous errors or there’s some way without having to wrap up all my routes?
If you are using "pure" Express, yes, it is the only way to do it, as this library does not support "asynchronous" error capture by default.
– Luiz Felipe
Does Voce use Try/catch in controller codes? because I always use it for whenever there is an error, async or not, I pass the error as parameter in next ( next(err) ) and have a function similar to your
handleError
to treat whatever the mistake is, so as not to have to staywrapAsync
on all routes. I don’t know if this can help you.– Cmte Cardeal
thank you, both responses were of utmost importance
– matheuslopess1