Error Handling in Express Middleware

A route can fail while Express handles a request, and the app still has to decide what response to send. Express error-handling middleware is a function that receives a failure passed from a route or other middleware and can send an error response.

I’ll show you how to add this middleware to an Express app and pass a route failure to it.

TL;DR

Express error-handling middleware receives failures that a route or other middleware passes into the error path, then sends one response or delegates the error onward.

  • Give the handler four parameters: error, request, response, and next.
  • Register it after routes and pass callback errors with next(error).
  • Express 5 forwards a rejected Promise returned by a handler, while Express 4 needs explicit forwarding or a wrapper.

What Is Error-Handling Middleware in Express?

Express recognizes error-handling middleware by the four-argument signature (err, req, res, next).

Request middleware can validate or enrich a request before a route sends its response.

FunctionSignatureWhat happens next
Request middleware(req, res, next)Continue with next() or finish the response.
Route handler(req, res)Send the route result or pass an error.
Error handler(err, req, res, next)Send an error response or call next(err).

Use next(‘route’) to skip the rest of a matching route, while next(err) sends a failure into Express error handling.

Any handler that does not call next(err) must finish the response, or the request stays open.

FailureTypical statusClient-facing response
Invalid request data400A validation message that identifies the input to fix.
Requested resource is missing404A short missing-resource message.
Unexpected server failure500A generic message. Keep diagnostics server-side.
Missing authentication401Ask the client to authenticate.
Authenticated but forbidden403Report the access decision without exposing protected details.
Conflicting resource state409Ask the client to refresh or resolve the conflict.

For a JSON API, keep response keys stable so clients can handle errors without parsing server-specific details. A browser-facing app can render an error page instead.

Use an app-level handler for a response format shared across routes. A router-level handler can apply a different policy to one endpoint group.

When you investigate a failure, keep its stack and safe cause in server-side logs. If your logging system adds a request ID, record it with the route, but omit authorization headers and credentials.

How to Add Error-Handling Middleware in Express Step by Step

A small app makes the order visible: define a route first, add the error handler after it, then make a request and inspect the status and JSON body. The example uses Express 5 and binds only to an ephemeral localhost port.

Step 1: Install Express and Check the Runtime

Express 5 requires Node.js 18 or newer, so check Node before creating the project. Initialize npm in a project directory and install Express without selecting a major or patch version.

node --version
npm init -y
npm install express
v26.7.0

up to date, audited 66 packages in 839ms

28 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

The install audited 66 packages and found zero vulnerabilities.

I checked the installed version with the package listing and got Express 5.3.0. The demo uses CommonJS, so the default npm project needs no module-type setting.

The package manager resolves its default release tag at install time, so another setup may fetch a later release. Check the installed version before running a tutorial against a project with a different dependency set.

node --version && npm list express --depth=0 --json
v26.7.0
{
  "version": "1.0.0",
  "name": "codeforgeek-error-handling-in-express-using-middleware-20261019t122902z-602f36f2edf9",
  "dependencies": {
    "express": {
      "version": "5.3.0",
      "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz",
      "overridden": false
    }
  }
}

Step 2: Route a Failure to the Error Handler

Save this as error-handler-demo.js in the project directory. The first route returns an order when its ID is 42 and throws a status-bearing error for another ID.

The handler checks whether a response has already started, accepts a valid 4xx or 5xx status when the error provides one, and hides an unexpected 5xx message from the client.

const express = require('express');

const app = express();

app.get('/orders/:id', async (req, res) => {
  if (req.params.id !== '42') {
    const error = new Error('Order not found');
    error.status = 404;
    throw error;
  }
  return res.json({ id: req.params.id });
});

app.get('/failure', async (req, res) => {
  throw new Error('Internal lookup failed');
});

app.use((err, req, res, next) => {
  if (res.headersSent) return next(err);
  const status = Number.isInteger(err.status) && err.status >= 400 && err.status <= 599 ? err.status : 500;
  const message = status < 500 ? err.message : 'Internal server error';
  return res.status(status).json({ error: message });
});

async function main() {
  const server = app.listen(0, '127.0.0.1');
  await new Promise((resolve) => server.once('listening', resolve));
  const { port } = server.address();
  try {
    for (const path of ['/orders/42', '/orders/missing', '/failure']) {
      const response = await fetch(`http://127.0.0.1:${port}${path}`);
      console.log(`GET ${path} -> ${response.status} ${JSON.stringify(await response.json())}`);
    }
  } finally {
    await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
  }
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Run the saved file from that project directory. It requests a known order, a missing order, and a generic route failure, then closes the listener in a finally block.

node error-handler-demo.js
GET /orders/42 -> 200 {"id":"42"}
GET /orders/missing -> 404 {"error":"Order not found"}
GET /failure -> 500 {"error":"Internal server error"}
Express route success, not-found and server-error responses in the terminal
The requests return HTTP 200 for an order, HTTP 404 for a missing order, and a generic HTTP 500 response.

I ran the three HTTP requests and received status 200 for the known order, 404 for the missing order, and 500 for the generic route failure. Those responses cover the success and error paths in the example.

RequestResponseReason
GET /orders/42200 with the order IDThe route found its expected resource.
GET /orders/missing404 with Order not foundThe failure is a client-visible missing resource.
GET /failure500 with Internal server errorThe thrown error has no trusted status.

This handler reads err.status, accepts only integer values from 400 through 599, and defaults other errors to 500. Normalize statusCode from upstream packages before calling it, and set known statuses where the route knows the failure type.

The test makes HTTP requests through Express instead of calling the handler directly. It therefore exercises route dispatch, status selection, and JSON serialization together.

The logged output gives a smoke check of the route. Add assertions for the status and JSON body, then verify that an unexpected 500 omits the thrown message.

Replace the hard-coded lookup with your application’s data access, then classify validation and persistence errors separately. The demo has no database or authentication layer, which keeps its 404 path deterministic.

I chose port zero because the operating system can select an available local port for the test. The finally block closes the listener even if a request fails, so the example does not leave a process running.

Express’s built-in handler remains the fallback for an error that this middleware passes onward. The sample delegates when headers have already been sent because a second response cannot replace bytes already written to the client.

Why Is Express Error Middleware Not Called?

I check the error source, handler signature, and whether headers have gone out, because each condition sends Express through a different path.

Parsers and authentication middleware can fail before a route runs. If they pass errors with next(err), the same app-level error path can format those failures too.

SymptomLikely causeFix
Express skips the functionThe function declares only three parameters.Declare (err, req, res, next), even if next is unused.
The default handler respondsThe custom handler was registered before the route, or no custom handler consumed the error.Register the error handler after routes that can fail.
A callback error never reaches ExpressThe callback reports the failure outside the route’s Promise chain.Pass its error to next(err).
An Express 4 async route escapesA rejected async handler needs explicit forwarding.Catch the rejection and call next(err), or use a wrapper that does so.
An Express 5 async route escapesThe route returned before a detached Promise or timer failed.Return the Promise from the route, then bridge callback or timer errors to next(err).
The request hangs after an errorThe error handler sent no response and did not pass the error onward.Finish the response or delegate to a later error handler.
The client receives a connection errorHeaders were already sent when the handler tried to write again.Check res.headersSent and return next(err) to Express’s default handler.
Express tries a different routeThe callback used next(‘route’) to skip its remaining route handlers.Use next(err) when the failure should enter error handling.

Express catches a synchronous throw from a route or middleware. Express 5 forwards a rejected Promise that a route returns, while Express 4 requires explicit forwarding through try/catch or a wrapper that calls next(err). Callback and timer work can finish outside that Promise, so catch those failures and pass them to next(err) while the request remains open.

A regular route can return a JSON 404 for an unmatched URL. Its response uses the normal routing path, where no handler has passed an error into Express.

If a custom handler only logs or classifies, call next(err) to reach the next error handler. Express’s built-in handler is the fallback, and its development output can include stack details that production suppresses. Test with the same NODE_ENV setting as deployment.

Conclusion: Forward the Error, Then Send One Response

Next, test the failure cases your routes can produce, including callback-based work or a response that has already started streaming.

Continue with CodeForGeek’s custom Express middleware guide for ordinary request checks, or its Express Router reference for router-level middleware. The Express error-handling guide documents version behavior and the headersSent handoff.

FAQ

These answers cover the signature and version details that change where Express sends a failure.

What is the Express error-handling middleware signature?

Use four parameters in this order: (err, req, res, next). Express recognizes the function as an error handler from that signature.

Does Express 5 catch async route errors?

Express 5 forwards a rejected Promise or thrown error from a route or middleware that returns a Promise. Callback-based work still needs its error passed to next(err).

How do you forward async errors in Express 4?

Catch the rejected Promise and pass the error to next(err), either in a try/catch block or in a wrapper that calls catch(next).

Where should the custom error handler go?

Register it after the routes and middleware that may pass errors to it. If response headers have already been sent, delegate with next(err).

What is the difference between next(‘route’) and next(err)?

next(‘route’) skips the remaining callbacks for the current route. next(err) sends the failure into Express error handling.

Should a 500 response include err.message?

Use a generic public message for an unexpected 500. Keep the diagnostic message and stack in server-side logs instead of exposing internal details.

Does an unmatched URL reach error middleware?

An unmatched URL follows normal routing. Add a regular fallback that sends a 404 response, and reserve error middleware for failures passed to next(err).

What should an error handler do when res.headersSent is true?

Do not try to write a second response. Call next(err) so Express can handle the failure after headers have already been sent.

How do I forward an error from a callback?

Call next(err) in the callback while the request is open. Express receives callback errors only when code explicitly sends them to the error path.

Why does a request hang after an error?

An error handler must send a response or pass the error to another handler with next(err). If it returns without either action, Express has no response to complete.

Pankaj Kumar
Pankaj Kumar

Pankaj Kumar is the founder and CEO of CodeForGeek, with more than 14 years in IT. He is an open-source enthusiast who enjoys sharing what he learns through CodeForGeek and YouTube, with a focus on Python, data analytics, machine learning, Angular, Node.js, and Kafka.

Articles: 337