Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Errors thrown in async Express handlers never reach the error handler

ErrorThe process exits with the error thrown inside an async route (an unhandled rejection)

Short answer

In Express 4 a rejected promise is not sent to next(), so an async handler that throws is an unhandled rejection that can crash the process. Express 5 forwards it for you. Both versions still miss promises you do not return, errors from callbacks, and error handlers that are missing, in the wrong place or never reply.

  • Applies to Express 4.21, Express 5, Node.js 22, Sequelize 6
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Add a route that throws inside an async function and call it. What happens tells you which Express version behaviour you are on: the process dying means rejections are not forwarded, an error response means they are.

    app.get('/boom', async (req, res) => {
      throw new Error('BROKEN');
    });
    // then: curl -i http://localhost:3000/boom
  2. 2Match what you see, then jump to its fix

    1. 1The process ends with the thrown error; your error middleware never runsExpress 4 does not pass a rejected promise to next()Fix
    2. 2The process ends with an unhandled rejection, even on Express 5A promise chain is started but not returnedFix
    3. 3The failing code uses a callback API (fs, a timer, an event listener) inside an otherwise async routeThe error comes from a callback, not from a promiseFix
    4. 4Errors reach Express but you still get the default stack-trace pageThe error handler is missing, in the wrong place, or has the wrong shapeFix
    5. 5The log shows the error, but the client waits until it times outYour error handler neither replies nor calls next()Fix

What does the error look like?

  • The process exits with the error thrown inside an async route (an unhandled rejection)
  • The browser gets Express's default error page with a stack trace instead of your own error response
  • A request never receives a response after an error was handled

Cause 1 of 5

Express 4 does not pass a rejected promise to next()

1Check

The Express 4 error-handling guide says errors from rejected promises are not passed to next automatically, async functions included. The rejection is unhandled, and on current Node.js versions that crashes the process. Check the installed version.

npm ls express

2Fix

Either catch the error yourself and call next(err), or move to Express 5, where a handler that returns a rejected promise has next called for it.

// Express 4
app.get('/users', async (req, res, next) => {
  try {
    const users = await User.findAll();   // Sequelize query
    res.json(users);
  } catch (err) {
    next(err);
  }
});

// Express 5: no try/catch needed, the same handler minus the catch
app.get('/users', async (req, res) => {
  res.json(await User.findAll());
});

3Verify

The boom route from the first step now answers with an error response instead of killing the process.

curl -i http://localhost:3000/boom

Confirmed by expressjs.com

Did this fix it?

Cause 2 of 5

A promise chain is started but not returned

1Check

Express 5 only knows about a promise the handler returns. A query written as .then() without a return and without a final catch is invisible to Express. Look for chains inside handlers that start with a database call.

grep -rn "\.then(" --include="*.js" --exclude-dir=node_modules routes/ src/

2Fix

Return the chain from the handler, or end it with .catch(next). With await, the async function itself is the returned promise.

app.get('/orders', (req, res, next) => {
  Order.findAll()
    .then((orders) => res.json(orders))
    .catch(next);
});

3Verify

Make the query fail on purpose, for example by querying a table that does not exist, and watch the error middleware receive it.

curl -i http://localhost:3000/orders

Confirmed by expressjs.com

Did this fix it?

Cause 3 of 5

The error comes from a callback, not from a promise

1Check

Errors from callback-based APIs are not thrown and are not part of any promise. The callback receives them as its first argument, and Express never sees them unless you pass them on.

grep -rnE "fs\.(readFile|writeFile|stat)\(" --include="*.js" --exclude-dir=node_modules .

2Fix

Pass the error to next() inside the callback, or switch to the promise form of the API and await it.

app.get('/file', (req, res, next) => {
  fs.readFile('/file-does-not-exist', (err, data) => {
    if (err) {
      next(err);
    } else {
      res.send(data);
    }
  });
});

3Verify

Request the route with a missing file; the error middleware runs.

curl -i http://localhost:3000/file

Confirmed by expressjs.com

Did this fix it?

Cause 4 of 5

The error handler is missing, in the wrong place, or has the wrong shape

1Check

An error-handling function has four arguments, (err, req, res, next), and must be defined after all other app.use() and route calls. Otherwise Express uses its built-in handler, which writes the error to the client with its stack trace outside production. Check the order in the main file.

grep -n "app.use\|app.get\|app.post\|app.listen" server.js

2Fix

Move the handler to the end, keep all four parameters, and hand over to the default handler when the headers have already gone out.

app.use((err, req, res, next) => {
  if (res.headersSent) {
    return next(err);
  }
  console.error(err.stack);
  res.status(500).json({ error: 'Something broke' });
});

3Verify

The boom route returns your JSON with status 500.

curl -i http://localhost:3000/boom

Confirmed by expressjs.com

Did this fix it?

Cause 5 of 5

Your error handler neither replies nor calls next()

1Check

When you do not call next in an error-handling function, you are responsible for writing and ending the response. If the handler only logs, the request hangs.

grep -n -B2 -A6 "(err, req, res, next)" server.js

2Fix

Finish every path of the handler with a response, or call next(err).

app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).send('Something broke!');
});

3Verify

The failing request ends at once with a 500 response.

curl -i --max-time 5 http://localhost:3000/boom

Confirmed by expressjs.com

Did this fix it?

How do I stop it coming back?

  • Write route handlers as async functions on Express 5, and as async functions with try/catch and next(err) on Express 4.
  • Return every promise from the handler, or end the chain with .catch(next).
  • Pass the error argument of every callback to next(err) before you touch the data.
  • Keep one error handler, last in the file, that always sends a response and checks res.headersSent.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Back end

Express crashes with ERR_HTTP_HEADERS_SENT

Error: Can't set headers after they are sent to the client

This error means your code tried to write headers or a second response after Express already sent one.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.