Error-Handling Middleware
Express recognizes a middleware function with four parameters (err, req, res, next) as a special error handler, run whenever next(err) is called or a synchronous error is thrown inside a route.
A Centralized Error Handler
Console Output
Click “Run” to see the console output here.
Triggering the Error Handler
Console Output
Click “Run” to see the console output here.
Async Errors Need next(err), Not Just throw
In older Express versions, a rejected Promise inside an async route handler does NOT automatically reach the error handler unless you explicitly catch it and call next(err) — an unhandled rejection just hangs the request. (Express 5 handles this automatically.)
A Wrapper to Avoid Repetitive try/catch
Console Output
Click “Run” to see the console output here.
Custom Error Classes
| Benefit | Example |
|---|---|
| Consistent status codes | class NotFoundError extends Error { status = 404 } |
| Easier to catch specific error types | if (err instanceof ValidationError) { ... } |
Best Practice
Define a small set of custom error classes (NotFoundError, ValidationError, UnauthorizedError) with a status property — it keeps error handling consistent and makes the centralized handler simple to reason about.