Custom Error classes and centralized handling
structured error design.
custom Error subclasses carry a statusCode and flag, the central handler inspects instanceof or statusCode to set the HTTP code and JSON shape, defaulting unknown errors to 500.
WHAT THIS TESTS Whether you can design a consistent error model and map domain errors to HTTP responses in one place.
A GOOD ANSWER COVERS Custom Error subclasses let an error carry the information needed to respond. A base ApiError extends Error and stores a statusCode and an isOperational flag; subclasses like NotFoundError or ValidationError set sensible defaults (404, 400). Throwing these from anywhere in the app means the call site declares intent without knowing about HTTP. The centralized error middleware then inspects each error: it reads err.statusCode (or uses instanceof checks) to pick the HTTP code and builds a uniform JSON body, for example { error: { message, code } }. Anything that is not a recognized operational error defaults to 500 with a generic message. In production you log the full error server-side but never send stack traces or internal details to the client; in development you may include more for debugging.
COMMON WRONG ANSWERS Returning HTTP 200 with an error payload, leaking stack traces to clients, mapping status codes inside every controller, or not defaulting unknown errors to 500.
LIKELY FOLLOW-UPS Operational versus programmer errors, why isOperational matters for shutdown decisions, consistent error envelopes, and logging strategy.
ONE CONCRETE EXAMPLE class ApiError extends Error { constructor(message, statusCode) { super(message); this.statusCode = statusCode; this.isOperational = true; } } class NotFoundError extends ApiError { constructor(m='Not found') { super(m, 404); } } The handler: app.use((err, req, res, next) => { const status = err.statusCode || 500; res.status(status).json({ error: err.isOperational ? err.message : 'Internal Server Error' }); }); A thrown NotFoundError yields a clean 404 JSON, while an unexpected TypeError yields a generic 500.
Read the original → expressjs.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.