Error Handling in Express.js the Right Way

Async handlers, custom error classes and one central middleware, so failures are logged and users get clean responses.
Unhandled errors crash Node.js processes or leak stack traces to users. A small, consistent setup prevents both.
Custom error classes
export class AppError extends Error {
constructor(status, code, message) {
super(message);
this.status = status;
this.code = code;
}
}
export const notFound = (what) => new AppError(404, "NOT_FOUND", `${what} not found`);Catch async errors
Express 5 forwards rejected promises from async handlers automatically. On Express 4, wrap handlers so thrown errors reach the error middleware instead of becoming unhandled rejections.
One central error middleware
app.use((err, req, res, next) => {
const status = err.status ?? 500;
if (status >= 500) logger.error({ err, path: req.path });
res.status(status).json({
error: {
code: err.code ?? "INTERNAL_ERROR",
message: status >= 500 ? "Something went wrong" : err.message,
},
});
});Rules I follow
- Expected errors, like validation and not found, are AppErrors with a clear code.
- Unexpected errors are logged with context and return a generic 500 message.
- Never send stack traces to clients in production.
- Crash on truly unknown process-level errors and let the process manager restart cleanly.
Make errors observable
Ship logs to a service you actually look at, and alert on spikes in 5xx responses. An error nobody sees is a bug that is still happening.









