Express 5 cheatsheet
Express 5: Error handling
3 common Express 5 tasks.
Handle errors in async routes
In Express 5, a rejected promise or thrown error in an async handler is passed to the error handler automatically.
app.get("/users/:id", async (req, res) => {
const user = await db.findUser(req.params.id);
res.json(user);
});
Add an error handler
Define it last. It takes four arguments.
app.use((err, req, res, next) => {
console.error(err);
res.status(500).json({ error: "Internal Server Error" });
});
Handle 404s
Add a catch-all after your routes.
app.use((req, res) => {
res.status(404).json({ error: "Not found" });
});