I have the following update endpoint which set some important metrics. It works fine, but some times it makes errors and then the app is crashed even through I’ve configured error middleware.
app.put('/ca-points', async (req, res) => {
const { id } = req.query.id;
await ComputePoints(id);
return res.send("ok");
});
app.use((err, req, res, next) => {
sentry.error(err);
return res
.status(500)
.json({ status: 500, message: "Something went wrong." });
});
So I need to use try/catch
on every controller?
user27276754 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2
Express doesn’t catch the errors that occurs in a asynchronous code until express 5 (which is in beta), you need to catch them and pass it to the next
function.
So your controller will be like this
app.put('/ca-points', async (req, res, next) => {
const { id } = req.query.id;
try {
await ComputePoints(id);
return res.send("ok");
}catch(e){
next(e)
}
});
If you are worried about wrapping every async
function with try/catch
block then you can use this package express-async-errors which makes express to catch async errors so you don’t need to change anything in your code.
0