Error Handling in APIs
Catch errors in one central place and return consistent, safe responses, instead of crashing the server or leaking internal details.
What is it?
Things go wrong all the time in a running backend. A database is briefly unreachable, a client sends malformed data, or a bug throws deep inside some function. If nothing catches these:
- The whole server process can crash, taking down every other request it was handling.
- The raw error, maybe with a stack trace or internal file paths, can leak back to the caller. That's unhelpful and a security risk.
Centralized error handling means one place, usually a special middleware, catches errors from anywhere in the app and turns them into a consistent, safe response. Routes don't each repeat that logic.
Explain like I'm 10
It's like one customer service desk in a large store, instead of every cashier handling every complaint. Whatever goes wrong, it's routed to that desk, which responds consistently and politely without exposing the store's internal problems.
Examples
A route that forwards its errors instead of crashing
app.get("/users/:id", async (req, res, next) => {
try {
const user = await db.users.findById(req.params.id);
if (!user) {
return res.status(404).json({ error: "User not found" });
}
res.json(user);
} catch (err) {
next(err); // hand off to centralized error-handling middleware
}
});Instead of letting a database error crash the process, the route catches it and passes it to a dedicated error handler.
Centralized error-handling middleware
app.use((err, req, res, next) => {
console.error(err); // log the full details internally
res.status(err.statusCode || 500).json({
error: "Something went wrong. Please try again.",
});
});Express treats this four-argument middleware as its error handler. It catches errors passed via next(err) from anywhere in the app, logs the full detail internally, and sends a safe, generic message to the caller.
How it works
Express tells middleware apart by the number of arguments. Normal middleware takes (req, res, next). Error-handling middleware takes four: (err, req, res, next).
When any route or middleware calls next(err), Express skips all remaining normal middleware and routes and jumps to the nearest error-handling middleware. There you decide what to log internally and what safe message to send back.
Why does it exist?
Without it, every route needs its own copy of the logic for catching errors, picking status codes, and hiding internal details. It's easy to miss one spot and leave a crash or a leak waiting to happen.
Centralizing it applies one policy everywhere and makes it much harder to expose a stack trace to a real user by accident.
When to use it
Add it to almost every real backend, from the start. It's cheap to set up early and expensive to retrofit once dozens of routes handle errors inconsistently.
When not to use it
It doesn't replace handling expected failures where they happen. A missing record (404) or invalid input (400) usually deserves its own specific response, not the generic handler meant for unexpected failures.
Common mistakes
Sending the raw error object (with its stack trace) to the client in production.
Forgetting to call
next(err)in an async route, so a thrown error is never caught and the process may crash.Treating every failure the same, instead of separating expected failures (bad input, missing resource) from unexpected ones (a bug, a downed dependency).
Practice exercises
- Easy:
Write a route that catches a thrown error and forwards it to
next(err)instead of crashing the server. - Medium:
Write error-handling middleware that logs the full error internally but returns only a generic message and status code to the client.
- Hard:
Design an error-handling scheme that separates 'expected' errors (like validation failures, with a custom
statusCode) from unexpected ones, and returns a different level of detail for each.
Interview questions
Why is centralized error handling important in an API?
It handles errors consistently everywhere, stops unhandled exceptions from crashing the server, and avoids leaking internal details like stack traces to clients.
How does Express know a middleware function is meant for error handling?
By its signature. Error-handling middleware takes four arguments, (err, req, res, next), instead of three.
What's the difference between an expected error and an unexpected one in API design?
An expected error (invalid input, a missing resource) is handled explicitly with a clear status and message. An unexpected error (a bug or crash) is caught generically, logged in detail, and reported to the client with a safe, vague message.
What happens if an `async` route handler throws in Express 4, but nothing catches it or forwards it with `next(err)`?
Express 4 doesn't catch a rejected promise from an async handler. It becomes an unhandled promise rejection that Express never sees, which can crash the process or leave the request hanging. (Express 5 fixes this by forwarding errors from async handlers to the error middleware automatically.)
How can you avoid manually wrapping every async route handler in its own try/catch?
Wrap each handler in a small helper (often called an async handler) that calls it and attaches .catch(next) to the returned promise. Any rejection then goes to next(err) without a try/catch in every route.
Why must error-handling middleware be registered last, after all other routes and middleware?
Express runs middleware in registration order. When something calls next(err), Express skips forward to the next error-handling middleware defined after that point. One placed earlier never sees errors from routes registered after it.
What's the difference between an operational error and a programmer error?
An operational error is an expected run-time problem in a working system, like a failed network request or invalid input, and can be handled gracefully. A programmer error is a bug, like calling a function with the wrong type. It generally shouldn't be caught and swallowed, since the program may be in an unknown state.
Why might letting the process crash on a programmer error be safer than catching it and returning a generic 500?
If a bug leaves the process in an undefined state, serving more requests risks further corruption or odd behavior. Crashing (with a process manager that restarts it) resets to a known-good state. Catching and continuing hides the bug.
What are `process.on("uncaughtException")` and `process.on("unhandledRejection")` for, and why don't they replace centralized Express error handling?
They're last-resort, process-wide safety nets for errors that escape everything else, usually used to log and exit cleanly. They run outside any request, so they can't send an HTTP response. Express's error middleware is tied to a request/response pair, so it's what actually replies to the caller.
How would you create a custom error class that carries an HTTP status code?
Extend Error and add a statusCode property, e.g. class ApiError extends Error { constructor(statusCode, message) { super(message); this.statusCode = statusCode; } }, then throw new ApiError(404, "Not found") and read err.statusCode in the error middleware.
Why is distinguishing a custom `ApiError` (with an explicit `statusCode`) from a plain `Error` useful inside centralized middleware?
Checking err.statusCode tells a deliberate failure (respond with its code and message) apart from an unexpected exception, which gets a generic 500 so a message never meant for users isn't exposed.
What HTTP status code should malformed or missing input receive, and why not 500?
400 Bad Request. The request is invalid, not the server's fault. A 500 signals the server failed, which blames the wrong side and can mislead monitoring that treats 500s as server-health incidents.
Why is returning a consistent JSON error shape across every endpoint valuable?
Callers (frontend code, other services, API consumers) can write one error-handling routine that works for every endpoint, with no special cases per route.
What's the risk of including the raw `err.message` from an unexpected exception directly in the response body?
An internal message can include sensitive detail, like a database error naming a table or part of a query. Send a generic message to the client and only log the real err.message internally.
Why does throwing synchronously inside a non-async route handler get caught automatically, while an async one doesn't in Express 4?
Express runs a handler inside its own try/catch, so a direct throw is caught and forwarded. A rejected promise from an async function happens after that call has already returned, outside Express's try/catch, so it's missed unless you forward it with .catch(next).
What does calling `next()` with no argument mean to Express, versus calling `next(err)`?
next() moves on to the next matching middleware or route as normal. next(err) signals a failure, so Express skips all remaining normal middleware and goes straight to error-handling middleware.
What's the difference between a 401 and a 403 status code?
401 Unauthorized means the caller hasn't proven who they are (missing or invalid credentials). 403 Forbidden means they're known but not allowed to do this action. Despite its name, 401 is about authentication, not authorization.
What's a correlation or request ID, and how does it help with error handling in production?
A unique ID attached to each request and included in every log line and error report for it. It lets you tie together scattered log entries across services or middleware when debugging one failed request.
Why might returning different error detail in development versus production be a good practice?
In development, the full stack trace and message speed up debugging. In production, that detail in the hands of a caller (or attacker) is a liability. A check like NODE_ENV can control how much the error handler includes.
If a route's `catch` block calls `next(err)` without a `return`, what happens to any code written after that call in the same handler?
It still runs. next(err) doesn't stop control flow by itself. Without return next(err), the handler can carry on and call res.json() a second time for the same request.
What does Express do if a handler calls `res.json()` (or similar) more than once for the same request?
It throws an error, usually "Cannot set headers after they are sent to the client". HTTP allows only one response per request. This often happens when a handler forgets to return after responding in one branch and then responds again.
How would you test that centralized error-handling middleware hides a raw error message from an unexpected exception?
Make a route throw a plain error (e.g. force a dependency to throw in a test). Assert the response has only the safe generic message and status code, never the original message or stack trace, and separately assert the full error was logged.
Why isn't it always safe to automatically retry a failed operation inside error-handling logic?
Retrying is only safe for idempotent operations, which give the same result however many times they run, like a GET. Retrying a non-idempotent one, like a payment charge or an INSERT with no deduplication, can perform the action more than once.
What's the difference between a synchronously thrown error and an error passed to a callback's error argument in older Node-style async code?
A synchronous throw travels up the call stack immediately and must be caught with try/catch at or above that point. An error-first callback's error argument doesn't throw at all. You must check it (if (err) { ... }) when the callback runs, long after the original try/catch is gone.
What's the value of a `notFoundHandler` middleware placed after all defined routes but before the error handler?
It catches requests that matched no route, so the app returns a consistent 404 JSON response for unknown endpoints instead of Express's default plain-text "Cannot GET /whatever" page.
Why still log the full error object, including its stack trace, inside error middleware even while returning a generic response to the client?
The stack trace and full message are what you need to find and fix the bug. Hiding them from the client is about not leaking internals to an untrusted caller, not throwing the information away. Capture it where the team looks, like logs or an error-tracking service.