Stop 04 · REST API Design with ExpressTopics · 5/9

Async Error Handling in Express

Part of the MERN Stack Roadmap

In short

Almost every route you write will await a database call. If that promise rejects and nothing catches it, Express 4 never hears about it and the request just hangs. Knowing how errors reach your middleware saves hours of confusion.

In Express 4 an error thrown inside an async route is not caught automatically, so you wrap handlers or use Express 5, which forwards rejected promises to your error middleware.

The jaadu, as a lifeguard on a tall chair, throws a ring buoy on a rope to a swimmer who has drifted past the flags.

Think of it like this

The lifeguard and the swimmers

The lifeguard can only rescue swimmers inside the flagged zone. In Express 4, async errors happen outside that zone, so you need a rope (a wrapper) to pull them back in. Express 5 widened the zone, so rejected promises reach the lifeguard on their own.

Watch it happen

Where a rejected promise goes

async handler
await DB call
promise rejects
next(err)
error middleware

1/5GET /api/products/abc runs an async function.

The big ideas

What you need to know

Express 4 misses async errors

Errors thrown in a sync handler are caught, but a rejected promise is not. You must forward it with next(err).

A wrapper fixes it

asyncHandler(fn) calls fn and attaches .catch(next), so every rejection reaches your error middleware.

Express 5 does it for you

Express 5 automatically forwards rejected promises from handlers and middleware to next(err).

Still need error middleware

Catching only moves the error. A four-argument error handler, registered last, decides the response.

See it in code

Walk through the code

js
1// Express 4: wrap every async handler2export const asyncHandler = (fn) => (req, res, next) =>3  Promise.resolve(fn(req, res, next)).catch(next);4 5router.get("/:id", asyncHandler(async (req, res) => {6  const product = await Product.findById(req.params.id);7  if (!product) throw new AppError(404, "NOT_FOUND", "Product not found");8  res.json(product);9}));10 11// Express 5: no wrapper needed12router.get("/:id", async (req, res) => {13  const product = await Product.findById(req.params.id);14  if (!product) throw new AppError(404, "NOT_FOUND", "Product not found");15  res.json(product);16});17 18// Both: register the error handler after all routes19app.use(errorHandler);

1/4The wrapper runs the handler and sends any rejection to next.

The same route in Express 4 and Express 5. Check your version with npm ls express.

Save yourself the pain

Common mistakes

Oops

Wrapping every handler body in try/catch and writing res.status(500) by hand.

Do this instead

Throw errors and let one wrapper or Express 5 forward them to a single error handler.

Oops

Writing res.json() and then also calling next(err) in the same request.

Do this instead

Send exactly one response. Either reply or pass the error on, never both.

Your mission

Make a hanging request fail properly

~20 min

Quick check

In Express 4, an async handler awaits a query that rejects, with no try/catch or wrapper. What happens?

Go deeper

  1. 1Write a small asyncHandler wrapper that catches errors and calls next(err).
  2. 2Check which Express version you use and how it treats async errors.
  3. 3Make a route throw on purpose and confirm the error handler responds.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge