

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Error-Handling Middleware
incomplete
2: Custom Errors
incomplete
This lesson's interactive features are locked, please to keep using them
Express allows you to capture and handle errors using special middleware. An error-handling middleware function has four parameters: (err, req, res, next).
async functions) are automatically passed to the error handler in Express 5.When an error reaches your error handler, you can respond with a 500 status code or any other status you choose.
function errorHandler(
err: Error,
req: Request,
res: Response,
next: NextFunction,
) {
console.error("Uh oh, spaghetti-o");
res.status(500).json({
error: "Boots has fallen",
});
}
app.use(errorHandler);
Error handling middleware needs to be defined last, after all your other app.use() and route handlers (app.post, app.get, etc.), but before app.listen.
In Express 5, unhandled async errors automatically go to the error handler.
app.post("/api", async (req, res) => {
await handler(req, res);
});
You can still use try/catch when you need to handle an error before re-throwing it.
app.post("/api", (req, res, next) => {
Promise.resolve(handler(req, res)).catch(next);
});
{
"error": "Something went wrong on our end"
}
Run and submit the CLI tests.