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

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.
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:
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:
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.

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 |
|---|---|---|---|---|---|
| returns | 1 | 0 | status | no failure log |
| throws exposed | 0 | 1 | status | one structured warning with code |
| rejects with database | 0 | 1 | status | one structured error retaining |
Trace the ownership row by row:
For
42, the promise fulfils and the route returns its only response. Route writes plus middleware writes are1 + 0 = 1.For
7, the returned promise rejects. Express 5 forwards the exposedAppError, normalisation preserves404, and the middleware answers. The count is0 + 1 = 1.For
13, normalisation wraps the database error as the internal cause, keeps status500, and hidesdb.internal:5432from the client. The count is0 + 1 = 1.
Every total is one, with no failure row writing in both layers.

Express double-response traps: why APIs hang or emit headers errors
Trap | What goes wrong | Repair |
|---|---|---|
| Handler and middleware both answer. | Use |
Send | Later code can throw after the response. | Use |
Call | An outer wrapper forwards it again. | Choose one bridge for that asynchronous unit. |
Ignore | Middleware tries to start fresh JSON after headers. | Use |
Log but neither send nor call | 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.
Keep learning
MongoDB Aggregation Pipeline: `$match` to `$group` with a Worked Example
Build one MongoDB aggregation pipeline step by step. Follow five fictional orders through filtering, array expansion, grouping, projection, and deterministic sorting.
Future Internet Explained: Architecture, a Worked IoT Example and Exam Traps
Learn how device, edge, network, cloud and application layers cooperate, then solve a smart-campus example for data reduction and control-loop latency.
Testing React Components: A Runnable Vitest and Testing Library Tutorial
Build and test a small React progress component from its initial render through completion. The examples use accessible queries, awaited actions, and an exact mock assertion.
React Performance Optimization Tutorial: Profiler, memo, useMemo, and useCallback Examples
Build one React lab, measure its render and calculation counts, then remove avoidable work while keeping typing responsive.





