Robust error handling separates amateur APIs from production-grade ones. Learn synchronous, asynchronous, and global error patterns.

Abdur Razzak
Full-Stack Web Developer
In Express, an error-handling middleware has four parameters: err, req, res, next. Register it after all other route handlers. When any route calls next(err), Express skips regular middleware and jumps straight to the error handler.
Unhandled async errors do not automatically reach Express error middleware. Wrap async route handlers in a try/catch and pass the error to next(), or use a utility like express-async-errors that patches Express to handle this automatically.
Create a custom AppError class that extends Error with a statusCode property. Throw AppError instances for expected failures (not found, forbidden) and let unexpected errors bubble up as generic 500 responses.
Operational errors (invalid input, resource not found) are expected and recoverable. Handle them gracefully and return meaningful HTTP responses. Programmer errors (null reference, type errors) indicate bugs — log them and crash the process rather than trying to recover.