Appearance
Errors and Logging
31. How does Express handle errors?
The short answer
When a route or middleware throws synchronously, calls next(err), or, in Express 5, returns a promise that rejects, Express stops running normal middleware and looks for the next error-handling middleware, one with four arguments. If you have not defined one, Express's built-in handler responds with status 500, or the error's own status, and in development includes the stack trace. In production you always define your own handler, so clients get a consistent, safe error format.
ts
app.get('/orders/:id', async (req, res) => {
const order = await orders.find(req.params.id) // (1) a database error rejects
if (!order) throw new NotFoundError('order', req.params.id) // (2) thrown on purpose
res.json(order)
})
app.use((err: unknown, req: Request, res: Response, _next: NextFunction) => { // (3)
// turn any error into a response; see question 35
})- An unexpected failure, such as the database being down, rejects the promise.
- An expected failure, thrown as a typed error.
- Both end up here, the central error handler.
The four ways an error reaches the handler:
| How | Caught in Express 4 | Caught in Express 5 |
|---|---|---|
throw in a synchronous handler | Yes | Yes |
next(err) | Yes | Yes |
Rejected promise from an async handler | No: hangs, and an unhandled rejection | Yes |
throw inside a callback or timer | No | No |
The default handler's behaviour: it logs to standard error, sends the status code, and includes the stack trace in the response body only when NODE_ENV is not production. Forgetting to set NODE_ENV=production therefore leaks stack traces to clients (question 39).
32. What is error-handling middleware, and why does it take four arguments?
The short answer
Error-handling middleware is a function with the signature (err, req, res, next). Express tells it apart from normal middleware purely by counting its parameters: four means "only call me when there is an error". Normal middleware is skipped once an error occurs, and error middleware is skipped when there is none. You register it with app.use after all routes, and you must declare all four parameters, even if you do not use next, or Express treats it as ordinary middleware.
ts
app.use((err: unknown, req: Request, res: Response, next: NextFunction) => { // (1)
if (res.headersSent) return next(err) // (2)
const status = err instanceof HttpError ? err.status : 500
res.status(status).json({ error: status === 500 ? 'internal_error' : (err as HttpError).code })
})- All four parameters declared. Removing
next, even though it looks unused, turns this into normal middleware that receives(req, res, next)in the wrong positions. - If a response has already started, it cannot be changed, so hand the error to Express's default handler, which closes the connection.
Why Express counts parameters. JavaScript functions have a length property equal to the number of declared parameters. Express checks fn.length === 4 when it registers the middleware. It is a quirky design, but it means no special registration function is needed.
You can chain several error handlers, for example one that logs and calls next(err), then one that formats the response.
33. How do you handle errors in asynchronous Express route handlers?
The short answer
In Express 5, write handlers as async functions and let errors throw: a rejected promise is passed to your error middleware automatically. In Express 4, that did not happen, so you either wrapped each handler's body in try/catch and called next(err), wrapped handlers in a helper that adds .catch(next), or used the express-async-errors package. In both versions, errors from callbacks and timers outside the promise chain must still be handled by hand.
ts
// Express 5: just throw or let the promise reject
app.post('/orders', async (req, res) => {
const order = await orders.create(req.user!.id, CreateOrder.parse(req.body)) // a ZodError or DB error is forwarded
res.status(201).json(order)
})
// Express 4: a wrapper does the forwarding
const asyncHandler =
(fn: (req: Request, res: Response, next: NextFunction) => Promise<unknown>) =>
(req: Request, res: Response, next: NextFunction) => {
fn(req, res, next).catch(next) // (1)
}
app.post('/orders', asyncHandler(async (req, res) => {
res.status(201).json(await orders.create(req.user!.id, req.body))
}))- Catch any rejection and pass it to
next, which sends it to the error middleware.
Still not caught, in either version:
ts
app.get('/report', (req, res) => {
setTimeout(() => { throw new Error('boom') }, 0) // crashes the process: outside the request's promise
})Wrap timer and callback APIs in promises and await them, so their errors join the normal flow.
Upgrading from 4 to 5: remove wrappers and express-async-errors once on Express 5, check route path syntax changes (the routing question), and check req.body handling (question 6).
34. What is express-async-errors, and when might it be used?
The short answer
express-async-errors is a small package for Express 4 that patches Express's router so rejected promises from async handlers are passed to the error middleware, as if you had called next(err). You import it once at start-up and stop writing wrappers. It is unnecessary in Express 5, which does this natively, and because it works by changing Express internals, it is best removed when you upgrade.
ts
import 'express-async-errors' // Express 4 only: import once, before defining routes
import express from 'express'
app.get('/orders/:id', async (req, res) => {
res.json(await orders.get(req.params.id)) // rejections now reach the error handler
})| Express version | Async errors | Need express-async-errors? |
|---|---|---|
| 4 | Not forwarded | Useful, or write wrappers |
| 5 | Forwarded automatically | No |
35. What is centralized error handling?
The short answer
Centralised error handling means every error in the application ends up in one place, the final error middleware, which decides the status code, the response body and how to log it. Routes and services simply throw meaningful errors, such as NotFoundError or ValidationError, without each formatting its own response. That gives clients one consistent error format, prevents internal details from leaking, makes logging uniform, and removes repeated try/catch blocks from handlers.
ts
export function errorHandler(logger: Logger) {
return (err: unknown, req: Request, res: Response, next: NextFunction) => {
if (res.headersSent) return next(err)
if (err instanceof ZodError) { // (1)
return res.status(400).json({ type: 'validation_error', issues: err.issues })
}
if (err instanceof HttpError && err.expose) { // (2)
if (err.status >= 500) logger.error({ err, requestId: res.locals.requestId }, err.message)
return res.status(err.status).json({ type: err.code, message: err.message })
}
logger.error({ err, requestId: res.locals.requestId, path: req.originalUrl }, 'unhandled error') // (3)
res.status(500).json({ type: 'internal_error', message: 'Something went wrong', requestId: res.locals.requestId }) // (4)
}
}- Validation errors become a
400with the list of problems. - Known, safe errors keep their status and message.
- Everything else is a bug or an outage: log it with full detail.
- The client gets a generic message and the request ID, which support can use to find the log line. The response format follows a single standard (question 61).
36. How do you create custom error classes?
The short answer
Extend the built-in Error class, set a clear name, and add the fields your error handler needs, such as an HTTP status, a stable machine-readable code, and whether the message is safe to show to clients. Build a small family from one base class, such as NotFoundError, ConflictError and ForbiddenError, so handlers can check with instanceof. Pass the original error as cause when wrapping, so the logs keep the root cause.
ts
export class HttpError extends Error {
constructor(
public readonly status: number,
public readonly code: string,
message: string,
public readonly expose = status < 500, // (1)
options?: { cause?: unknown },
) {
super(message, options) // (2)
this.name = new.target.name // (3)
}
}
export class NotFoundError extends HttpError {
constructor(resource: string, id: string) {
super(404, `${resource}_not_found`, `${resource} ${id} was not found`)
}
}
export class ConflictError extends HttpError {
constructor(code: string, message: string) { super(409, code, message) }
}
// using them
try {
await db.orders.insert(order)
} catch (err) {
if (isUniqueViolation(err)) throw new ConflictError('order_exists', 'An order with this reference already exists')
throw new Error('saving order failed', { cause: err }) // (4)
}expose: client errors, below 500, are safe to show; server errors are not.causekeeps the original error and its stack for the logs.new.target.namesets the name to the actual subclass, such asNotFoundError, which appears in logs.- Wrapping an unexpected error adds context without losing the original.
Stable codes beat messages. Clients and front-end translations should rely on code: 'order_exists', which never changes, not on the English message, which you might reword.
37. What is the difference between operational errors and programming errors?
The short answer
Operational errors are expected problems in a correctly written program, caused by the outside world: invalid input, a missing record, a network timeout, a full disk, a declined card. You handle them: return a clear response, retry, or degrade gracefully. Programming errors are bugs in your code, such as reading a property of undefined, calling a function with the wrong arguments, or a broken assumption. You cannot sensibly handle them at runtime; you log them, return a generic 500, and fix the code, and if the process state might be corrupted, restart it.
| Operational | Programming | |
|---|---|---|
| Cause | The environment or the input | A bug |
| Examples | ECONNREFUSED, validation failure, 404, timeout | TypeError: Cannot read properties of undefined |
| Expected? | Yes | No |
| Response | Handle: retry, 4xx, fallback | Log, generic 500, fix the code |
| Process | Keep running | Consider restarting if state may be broken |
Why the distinction matters: treating a bug like an operational error, for example retrying it, just repeats the bug. Treating an operational error like a bug, for example crashing because the payment provider timed out once, makes the service fragile.
ts
try {
return await paymentApi.charge(order)
} catch (err) {
if (isTimeout(err)) throw new HttpError(503, 'payment_unavailable', 'Payment provider is busy, try again', true) // operational
throw err // unknown: let it surface
}38. How should errors be logged in a production application?
The short answer
Log errors as structured JSON with a consistent set of fields: the message, error name, stack trace, cause, a request ID or trace ID, the route, the user or tenant ID where allowed, and a severity level. Write to standard output and let the platform ship logs to a central store. Log each error once, at the place that handles it, not at every layer. Never log passwords, tokens, card numbers or other secrets, and redact them automatically. Alert on rates of errors, not on single log lines.
ts
import pino from 'pino'
export const logger = pino({
level: config.LOG_LEVEL,
redact: ['req.headers.authorization', 'req.headers.cookie', '*.password', '*.cardNumber'], // (1)
serializers: { err: pino.stdSerializers.err }, // (2)
})
logger.error(
{ err, requestId: res.locals.requestId, route: req.route?.path, userId: req.user?.id }, // (3)
'failed to create order',
)- Redaction replaces sensitive fields with
[Redacted]before anything is written. - The error serialiser includes the name, message, stack and
cause. - Context fields make the line searchable: all errors for one request, one route or one user.
A typical log line:
json
{"level":50,"time":1793088000123,"requestId":"9f1c…","route":"/orders","userId":"u_17","err":{"type":"Error","message":"saving order failed","stack":"Error: saving order failed\n at …","cause":{"code":"ECONNRESET"}},"msg":"failed to create order"}Habits that keep logs useful:
| Do | Avoid |
|---|---|
| One line per event, as JSON | Multi-line text that log tools split |
| Log once, where the error is handled | Logging the same error at every layer |
| Include request and trace IDs | Lines that cannot be tied to a request |
Levels: error for failures, warn for odd but handled | Everything at error, so real problems drown |
| Redact automatically | Relying on people to remember |
39. How do you prevent stack traces and sensitive details from leaking to clients?
The short answer
Never send raw error objects or messages from unexpected errors to clients. Use a central error handler that returns a generic message and a request ID for every 500, and only passes through messages from errors you explicitly marked as safe. Set NODE_ENV=production, so Express's default handler hides stack traces. Do not echo database or third-party error messages. Remove headers that reveal your stack, such as X-Powered-By, and keep detailed information in logs only.
What leaks look like, and why they matter:
json
{
"error": "duplicate key value violates unique constraint \"users_email_key\"",
"stack": "at Parser.parseErrorMessage (/app/node_modules/pg-protocol/dist/parser.js:287:98)…"
}This tells an attacker the database type, table and column names, file paths and library versions, which help them plan an attack, and it confirms that a given email address has an account.
The fixes:
| Leak | Fix |
|---|---|
| Stack traces in responses | Central handler; NODE_ENV=production |
| Database error messages | Map known ones, such as a unique violation, to your own message; hide the rest |
X-Powered-By: Express | app.disable('x-powered-by'), or Helmet |
| Detailed validation of login | "Email or password is incorrect", not "no user with that email" |
| Third-party error bodies | Wrap them in your own error type |
Safe messages are an explicit decision: the expose flag on known errors (question 36). Anything not marked safe becomes "Something went wrong" plus the request ID.
40. How do global exception and unhandled rejection handlers work in Node.js?
The short answer
process.on('uncaughtException') runs when an error is thrown and nothing catches it, and process.on('unhandledRejection') runs when a promise rejects with no handler attached. They are a last resort, not error handling: after an uncaught exception, the process may be in a broken state, so the right action is to log the error with full details, stop accepting new work, finish or abort in-flight requests within a deadline, and exit with a non-zero code, so the supervisor or orchestrator starts a fresh process.
ts
process.on('unhandledRejection', (reason) => {
logger.fatal({ err: reason }, 'unhandled promise rejection')
shutdownGracefully(1) // (1)
})
process.on('uncaughtException', (err, origin) => {
logger.fatal({ err, origin }, 'uncaught exception')
shutdownGracefully(1)
})
function shutdownGracefully(code: number) {
setTimeout(() => process.exit(code), 10_000).unref() // (2) never hang for ever
server.close(() => process.exit(code))
}- Log, then shut down cleanly. Since Node.js 15, an unhandled rejection crashes the process by default; with a handler, you decide, and you should still exit.
- A hard deadline in case connections never close.
Why not just carry on? The error interrupted some code halfway, which may have left a lock held, a transaction open or an object half updated. Serving more requests from that state can corrupt data. Restarting is cheap when several instances run behind a load balancer.
These handlers are not a substitute for handling errors where they happen (the unhandled rejection question).
41. How do Morgan, Winston, and Pino differ, and when would you use them?
The short answer
Morgan is Express middleware that only logs HTTP requests, one line per request, usually in a text format such as the Apache combined log. Winston is a general-purpose application logger, flexible and configurable, with many transports for sending logs to files and services, but slower. Pino is a general-purpose logger focused on speed and structured JSON output, with pino-http for request logging and built-in redaction. For new production services, Pino with pino-http covers both jobs; Morgan is fine for quick text request logs in development.
| Morgan | Winston | Pino | |
|---|---|---|---|
| Purpose | HTTP request logs only | Any application logs | Any application logs, plus pino-http |
| Output | Text by default | Configurable: text or JSON | JSON |
| Speed | Fine | Slower | Very fast |
| Transports | Writes to a stream | Many built in | Run in a worker thread |
| Redaction | No | Custom formats | Built in |
| Typical choice | Development, simple apps | Teams already using it, complex routing of logs | New production services |
ts
// development: readable request lines
app.use(morgan('dev')) // GET /orders/42 200 12.3 ms - 412
// production: structured request and application logs with one logger
import pinoHttp from 'pino-http'
app.use(pinoHttp({ logger, customProps: (_req, res) => ({ requestId: res.locals.requestId }) }))Why logger speed matters: logging runs on the main thread for every request. A slow logger, or very verbose logging, adds latency to every response and can become a measurable share of CPU (the high CPU question). Write JSON to standard output and let a separate agent ship it.