DevAcademy
LearnNode.jsError Handling in Express
IntermediateNode.js

Error Handling in Express

Centralize error handling with a dedicated error-handling middleware instead of scattering try/catch everywhere.

Reading Time

14 min

Lesson

Lesson 24 of 34

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

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Triggering the Error Handler

Try it yourself — edit and run

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

Try it yourself — edit and run

Console Output

Click “Run” to see the console output here.

Custom Error Classes

BenefitExample
Consistent status codesclass NotFoundError extends Error { status = 404 }
Easier to catch specific error typesif (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.

Interview Questions

Quick Quiz

1. How does Express recognize an error-handling middleware?

2. In older Express versions, what happens to an unhandled rejected Promise in an async route handler?

3. Where must error-handling middleware be registered relative to routes?