We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Error-Handling Middleware

Express allows you to capture and handle errors using special middleware. An error-handling middleware function has four parameters: (err, req, res, next).

  1. Synchronous errors (thrown in your route handlers) automatically skip normal middleware and go straight to this error handler.
  2. Asynchronous errors (in 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.

Catching Errors in Async Code

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);
});

Assignment

{
  "error": "Something went wrong on our end"
}

Run and submit the CLI tests.