Express Async Error Handling: One Reliable Failure Path Without Double Responses

Build one Express failure path that forwards rejected work once, protects internal causes, and prevents hangs and double responses. Trace three deterministic requests from route to log and client.

KnowledgeGate Team

Exam prep & CS education

Updated 17 Nov 20266 min read
Express Async Error Handling: One Reliable Failure Path Without Double Responses

A route awaits database work, then a rejection makes the API hang, crash, leak an internal message, or try a second response. Scattered try/catch blocks do not create a contract while callbacks, primitive rejections, and partially sent responses escape by different paths. The invariant is one success response or one forwarded failure: expected operational errors become controlled client responses, unknown failures become safe 500s, and real causes stay in the internal log. Express 5 forwards a returned rejected promise to next; Express 4 requires an explicit promise wrapper.

Express async errors: draw the boundary around every route

Three failure origins matter. A synchronous throw enters Express error handling. In Express 5, rejection of an async handler's returned promise enters it too. A later callback such as setTimeout(() => { throw new Error('BROKEN'); }, 10) is outside that promise. Convert it to a promise and await it, or catch inside it and call next(err) once.

Node.js failures also arrive through callbacks, streams, and process-level events; Node.js Error Handling Tutorial: Patterns and Worked Examples maps those channels. Express response ownership is narrower: a returned route rejection must reach four-parameter middleware exactly once in Express 4 or Express 5.

js
app.get('/orders/:id', async (req, res) => {
  const order = await orderService.find(req.params.id);
  return res.status(200).json({ data: order, requestId: req.id });
});

The route has no success-path catch or fallback after failure. In Express 4, add one explicit boundary:

js
const asyncHandler = fn => (req, res, next) =>
  Promise.resolve(fn(req, res, next)).catch(next);

app.get('/orders/:id', asyncHandler(getOrder));

Do not call next(err) inside a catch and then rethrow. The wrapper would observe the same rejection and forward it again. Let the wrapper catch it, or consume it inside the route, never both.

Express error contract: operational errors versus unknown failures

A controlled AppError has message, integer status, stable string code, Boolean expose, and optional cause. An invalid ID uses { status: 400, code: 'INVALID_ORDER_ID', expose: true }; a missing order uses { status: 404, code: 'ORDER_NOT_FOUND', expose: true }. An unexpected TypeError, driver error, or primitive rejection becomes { status: 500, code: 'INTERNAL_ERROR', expose: false }.

normalizeError(reason) returns an AppError unchanged. Otherwise it preserves an existing Error as the cause. For a primitive such as 'DB_POOL_EXHAUSTED', it first creates new Error('Non-Error rejection: DB_POOL_EXHAUSTED'), then returns new AppError('Internal server error', { status: 500, code: 'INTERNAL_ERROR', expose: false, cause }).

Only a controlled error with expose: true may supply its message to client JSON. Stacks, query text, hostnames, and unknown messages belong only in the structured log.

Express error middleware: assemble the path in the only safe order

Register components in this order: request-ID middleware, JSON parser, routes, no-route handler, then error middleware. The no-route handler creates AppError('Route not found', { status: 404, code: 'ROUTE_NOT_FOUND', expose: true }). The last middleware must retain all four parameters: function errorHandler(reason, req, res, next).

Its first line of control is if (res.headersSent) return next(reason);. Otherwise, normalise once, log once, and answer once:

js
const err = normalizeError(reason);
const level = err.status >= 500 ? 'error' : 'warn';
logger[level]({
  requestId: req.id,
  code: err.code,
  status: err.status,
  cause: err.cause ?? err
});

return res.status(err.status).json({
  error: {
    code: err.code,
    message: err.expose ? err.message : 'Internal server error'
  },
  requestId: req.id
});

The route owns success. Error middleware owns failure before headers. Downstream or default Express handling owns failure after headers. No branch has two owners.

Left-to-right Express 5 request pipeline shows successful order 42 handling, 404 and 500 error convergence, headers-sent bypass, and single response ownership.

Express async error worked example: trace IDs 42, 7 and 13

Use three fixed outcomes to count every response write. For ID 42, the service returns { id: 42, itemCount: 3, state: 'READY' }. For ID 7, it throws AppError('Order 7 was not found', { status: 404, code: 'ORDER_NOT_FOUND', expose: true }). For ID 13, it rejects with new Error('connect ETIMEDOUT db.internal:5432').

Request and request ID

Service outcome

Route writes

Error middleware writes

Exact client result

Internal result

GET /orders/42, req-42

returns {id:42,itemCount:3,state:'READY'}

1

0

status 200, {"data":{"id":42,"itemCount":3,"state":"READY"},"requestId":"req-42"}

no failure log

GET /orders/7, req-7

throws exposed AppError

0

1

status 404, {"error":{"code":"ORDER_NOT_FOUND","message":"Order 7 was not found"},"requestId":"req-7"}

one structured warning with code ORDER_NOT_FOUND

GET /orders/13, req-13

rejects with database Error

0

1

status 500, {"error":{"code":"INTERNAL_ERROR","message":"Internal server error"},"requestId":"req-13"}

one structured error retaining connect ETIMEDOUT db.internal:5432

Trace the ownership row by row:

  • For 42, the promise fulfils and the route returns its only response. Route writes plus middleware writes are 1 + 0 = 1.

  • For 7, the returned promise rejects. Express 5 forwards the exposed AppError, normalisation preserves 404, and the middleware answers. The count is 0 + 1 = 1.

  • For 13, normalisation wraps the database error as the internal cause, keeps status 500, and hides db.internal:5432 from the client. The count is 0 + 1 = 1.

Every total is one, with no failure row writing in both layers.

Three aligned sequence traces show order 42 succeeding with 200, order 7 producing 404, and order 13 producing a safe 500 response.

Express double-response traps: why APIs hang or emit headers errors

Trap

What goes wrong

Repair

next(err); res.status(500).json(...)

Handler and middleware both answer.

Use return next(err) with no response below.

Send res.json(order), then continue

Later code can throw after the response.

Use return res.json(order) and move later work out of the request path.

Call next(err), then rethrow

An outer wrapper forwards it again.

Choose one bridge for that asynchronous unit.

Ignore res.headersSent after streaming starts

Middleware tries to start fresh JSON after headers.

Use if (res.headersSent) return next(reason);.

Log but neither send nor call next

The request stays open.

End with one returned success or one returned or thrown failure.

Once HTTP status and headers are sent, they cannot restart as a second response. The Application Layer Protocols: DNS and HTTP Guide explains the wider protocol boundary.

Express error-path tests: assert the contract, not just the status

Use the same fixture and request IDs in integration tests. For /orders/42, assert status 200, its exact table body, serviceCalls = 1, errorHandlerCalls = 0, and failureLogCalls = 0. For /orders/7, assert status 404, its exact body, serviceCalls = 1, errorHandlerCalls = 1, and one warning log. For /orders/13, assert status 500, its safe exact body, errorHandlerCalls = 1, and one error log whose cause contains ETIMEDOUT.

For both failures, assert that client JSON contains no stack, db.internal, 5432, or ERR_HTTP_HEADERS_SENT. Each request must complete. For the 500, require requestId: 'req-13', code: 'INTERNAL_ERROR', and status: 500 in the log, proving observability survived redaction.

Add one callback regression test. Replace a raw timer throw with an awaited promise that rejects after 10 ms, then assert one safe 500 from the same middleware. The 10 ms value is only a deterministic test delay, not a latency target or benchmark.

Express async errors in interviews and code review

Practise four concrete prompts: explain why Express 5 catches a rejected async handler but not an unrelated timer throw; add the Express 4 wrapper; classify ID 7 as operational and ID 13 as unknown; find the double response in next(err); res.json(...).

A strong answer traces ownership instead of merely saying “use middleware”. It names who writes for req-42, req-7, and req-13, what reaches the client, and what remains in the log. Treat these as realistic debugging, interview, and project-review exercises.

Express async error handling: the short version and next step

Return the handler promise. Bridge callbacks once. Throw controlled operational errors. Normalise unknown values to a non-exposed 500. Let exactly one layer own the response, and let res.headersSent delegate instead of starting new JSON.

Now add /orders/abc and make it produce controlled 400 INVALID_ORDER_ID, then run all four route tests and account for every response write. Continue with the Node.js, Express.js & MongoDB Course for focused backend learning, use MERN Stack for the broader full-stack path, or browse Skill Development Courses for the wider catalogue.