Express Async Error Handling Wrapper
Route async failures into Express error middleware with a wrapper, classify status codes, and mask internal details before responding.
Code
import express from 'express';
class HttpError extends Error {
constructor(status, message, public detail = null) {
super(message);
this.status = status;
this.detail = detail;
}
}
const wrap = (handler) => (req, res, next) => {
Promise.resolve(handler(req, res, next)).catch(next);
};
const app = express();
app.use(express.json());
app.get('/orders/:id', wrap(async (req, res) => {
const order = await findOrder(req.params.id);
if (!order) throw new HttpError(404, 'order not found');
res.json(order);
}));
app.use((err, req, res, next) => {
const status = err instanceof HttpError ? err.status : 500;
if (status >= 500) console.error('unhandled:', err.stack);
res.status(status).json({
error: err.message || 'internal error',
detail: status < 500 ? err.detail : undefined,
});
});
async function findOrder(id) {
if (id === 'missing') return null;
return { id, total: 42 };
}
app.listen(3000);How it works
Count the class HttpError and the functions wrap and findOrder as the entire surface area of Express Async Error Handling Wrapper.
Every asynchronous step is awaited, so rejections surface where the call happens. Instead of silently continuing, the code raises HttpError at the guard.
The result comes back as an object carrying id.
Caveats
- External dependency:
express— install it before running the snippet. - The guard
!ordershort-circuits the flow with an earlythrowwhen its condition holds.
Putting it to use
Entry signature: const wrap = (handler)
The demo output is labeled (unhandled:), so every printed line maps back to its originating operation.
The call returns id.
Core lines
Promise.resolve(handler(req, res, next)).catch(next);
if (!order) throw new HttpError(404, 'order not found');
const order = await findOrder(req.params.id);
Interactive Tools for This Topic
FAQ
- Does `wrap` modify its input?
- No mutation happens — the function reads its input and returns a new value.
- What happens on invalid input?
- Validation comes first — `HttpError` marks the failure at `!order`, before any partial work happens.
- Are there third-party dependencies?
- `express` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.