Express error handling
Framework lane: Express 5.x (Supertest required for integration test). Exact supported patch, dependency lock, advisory review and execution are NOT RUN. The framework code is a static candidate; do not install dependencies or expose a server automatically. The local companion uses Node.js 22.16.0 and requires no third-party packages.
Framework example — staged
import express from 'express';const app = express();app.get('/catalog', async () => { throw new Error('Storage unavailable'); });app.use((req, res) => res.status(404).json({ code: 'NOT_FOUND' }));app.use((err, req, res, next) => { if (res.headersSent) return next(err); res.status(500).json({ code: 'INTERNAL_ERROR' });});export default app;Expected behavior (not observed): GET /catalog should return 500 with a generic code. GET /missing should return 404. The internal exception message should not appear.
How it works
Express 5 forwards thrown errors and rejected promises returned by route handlers to error middleware. Detached asynchronous work still needs explicit ownership. Register a not-found handler after normal routes, then an error handler with four parameters. If headers are already sent, delegate instead of trying to rewrite the response. Never send arbitrary internal exception messages to clients.
Practice the underlying idea without dependencies
function publicError(code) { if (code === 'NOT_FOUND') return { status: 404, code }; return { status: 500, code: 'INTERNAL_ERROR' };}console.log(JSON.stringify(['NOT_FOUND','database path'].map(publicError)));Run node main.mjs in a disposable directory. Expected output:
[{"status":404,"code":"NOT_FOUND"},{"status":500,"code":"INTERNAL_ERROR"}]This tests the illustrated JavaScript behavior only, not the framework.
Common mistake
The 404 handler is ordinary middleware, not an exception handler. In a real app map known parser failures such as oversized input to appropriate 4xx responses; this minimal app only demonstrates internal errors.
Apply it yourself
Add a controlled domain error code for unavailable inventory and design a safe response without exposing private details.
Further reading
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Express error handling — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
What identifies error middleware?
What should happen if headers are already sent?
What is a suitable public response to an unexpected storage failure?