Search code examples
node.jsexpress

Express Error middleware doesn't catching errors


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?


Solution

  • 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.