Sub topic 14
Where to Catch, Log, or Let Errors Propagate
The earlier chapters covered the mechanics: try, catch, finally, custom error classes, instanceof checks, the cause option, promise rejections, and global handlers. This chapter is about judgment. For any error, it asks where in your code it should be caught, who should log it, and when it is better to let it travel up the call stack untouched.
This chapter assumes you can write custom Error subclasses, use async/await, and run scripts in Node.js 16.9 or later. That version is needed because the examples use the cause option.
The Core Question: Can This Code Do Something Useful?
When a function calls something that might throw, it has three real options:
- Handle it. Recover by returning a fallback, retrying, or showing the user a message. Use this only when the function actually knows a sensible way to continue.
- Add context and rethrow. Wrap the error with
causeso that the next layer up learns what this code was trying to do when it failed. - Let it propagate. Write no
tryat all. The error passes up to a caller that knows more.
Option 3 is the default, and it is often the right one. A catch block that cannot do anything useful only adds noise and can hide the problem.
Expected Failures vs. Bugs
It helps to sort errors into two groups, because each group is handled differently.
| Kind | Examples | Typical handling |
|---|---|---|
| Expected (operational) failures | Network timeout, record not found, invalid user input, file missing | Catch close to where you can respond, often with a custom error class |
| Bugs (programmer errors) | `TypeError` from reading a property of `undefined`, wrong argument types, broken invariants | Do not recover. Let them reach a boundary, log them, and fix the code |
Expected failures belong to your program's normal behavior. A login form will receive wrong passwords. Bugs mean the code is wrong, and "recovering" from a bug usually means running on with corrupted state. This is why the catch blocks in earlier chapters checked instanceof for specific classes and rethrew everything else. A blanket catch that treats a TypeError like a "user not found" turns a crash you could see into wrong behavior nobody notices.
Boundaries: Where Errors Should End Up
A boundary is a point where your code hands control back to something outside it. Common boundaries are:
- An HTTP request handler, which must send some response.
- A UI event handler, which must leave the interface usable.
- A job or queue worker, which must mark the job failed.
- The program's entry point (
main), which must exit with a status code. - Global handlers, the last-resort net covered in the previous chapter.
Boundaries are where errors get logged and turned into a response. Lower layers should mostly let errors through or add context. The example below shows all three roles in a small, runnable program.
class NotFoundError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'NotFoundError';
}
}
const db = new Map([[1, { id: 1, name: 'Ada' }]]);
// Data layer: reports failures, knows nothing about HTTP, does not log.
async function findUser(id) {
if (!Number.isInteger(id)) {
throw new TypeError(`id must be an integer, got ${typeof id}`);
}
const user = db.get(id);
if (!user) throw new NotFoundError(`No user with id ${id}`);
return user;
}
// Service layer: adds context to unexpected failures, does not log.
async function getGreeting(id) {
try {
const user = await findUser(id);
return `Hello, ${user.name}`;
} catch (err) {
if (err instanceof NotFoundError) throw err; // already meaningful
throw new Error(`getGreeting failed for id ${id}`, { cause: err });
}
}
// Logs an error and every error in its cause chain.
function logError(err) {
let current = err;
let label = 'Error';
while (current !== undefined) {
const text = current instanceof Error
? `${current.name}: ${current.message}`
: String(current);
console.error(`${label}: ${text}`);
current = current instanceof Error ? current.cause : undefined;
label = 'Caused by';
}
}
// Boundary: decides the response and logs exactly once.
async function handleRequest(id) {
try {
const body = await getGreeting(id);
return { status: 200, body };
} catch (err) {
if (err instanceof NotFoundError) {
return { status: 404, body: err.message }; // expected, no log needed
}
logError(err);
return { status: 500, body: 'Internal error' };
}
}
(async () => {
console.log(await handleRequest(1)); // { status: 200, body: 'Hello, Ada' }
console.log(await handleRequest(2)); // { status: 404, body: 'No user with id 2' }
console.log(await handleRequest('x')); // logs the chain, then { status: 500, ... }
})();The third call prints:
Error: Error: getGreeting failed for id x
Caused by: TypeError: id must be an integer, got string
{ status: 500, body: 'Internal error' }Look at how the work is split. findUser throws and does nothing else. getGreeting adds one sentence of context. Only handleRequest knows what "failure" means to the caller, so only it logs and builds a response. The 404 is an expected outcome and is not logged as an error.
Log Once, Where the Error Is Handled
A common anti-pattern is catch-log-rethrow at every layer:
async function getProfile(id) {
try {
return await findUser(id);
} catch (err) {
console.error('getProfile failed', err); // logged here...
throw err; // ...and again by every caller
}
}If three layers do this, one failure shows up as three log entries. That makes it hard to count incidents and easy to misread one problem as several. If a layer has context to add, put it in the error with cause and let the boundary log the whole chain once.
Anti-Patterns to Avoid
Swallowing errors
function loadSettings(text) {
try {
return JSON.parse(text);
} catch (err) {
return null; // why did it fail? Nobody will ever know
}
}Returning null or {} is fine when it is a deliberate fallback. The parseConfig example from the first chapter is one. In that case, document it, and log or count it if the failure matters operationally. An empty catch {} with no comment is almost always a bug waiting to happen.
Wrapping too much code in one try
A large try block catches errors from lines you never meant to guard, including bugs. Keep the try around just the call that can fail in the way you expect:
function readPrefs(raw) {
let prefs;
try {
prefs = JSON.parse(raw); // the only line expected to fail
} catch (err) {
if (!(err instanceof SyntaxError)) throw err;
return { theme: 'light' };
}
// A bug down here is not silently turned into the default.
return { theme: prefs.theme ?? 'light' };
}
console.log(readPrefs('{"theme":"dark"}')); // { theme: 'dark' }
console.log(readPrefs('garbage')); // { theme: 'light' }Throwing non-Error values
throw 'failed' or throw { code: 42 } works, but these values have no stack, instanceof Error checks fail, and the logError loop above can only print them as strings. Always throw Error instances or subclasses.
Losing the original error
Writing throw new Error('Save failed') inside a catch without { cause: err } throws away the stack and message that explain the real problem. If you replace an error, chain it.
Async Code: No Promise Left Behind
The previous chapters showed that an un-awaited rejected promise never reaches your try/catch. The practical rule: every promise must be awaited, returned, or given a .catch().
Fire-and-forget work, such as analytics or cache warming, is the case people get wrong most often. If its failure should not affect the main flow, say so explicitly:
async function sendAnalytics(event) {
throw new Error('analytics service down');
}
function onClick() {
// Not awaited on purpose: the click should not wait for analytics.
sendAnalytics({ type: 'click' }).catch((err) => {
console.warn('Analytics failed, ignoring:', err.message);
});
console.log('Click handled');
}
onClick();
// Click handled
// Analytics failed, ignoring: analytics service downWithout the .catch(), this becomes an unhandled rejection. Node.js 15 and later terminate the process by default when that happens.
Use `finally` for Cleanup Regardless of Where You Catch
Deciding not to catch an error does not mean skipping cleanup. A function can let an error propagate and still release its resources:
async function withLock(lock, task) {
lock.held = true;
try {
return await task();
} finally {
lock.held = false; // runs on success and on failure
}
}
const lock = { held: false };
withLock(lock, async () => { throw new Error('task failed'); })
.catch((err) => console.log(err.message, '| lock held:', lock.held));
// task failed | lock held: falsetry/finally with no catch is a common and correct pattern: clean up here, and let the caller decide what the failure means.
A Checklist
- Catch only when you can recover, add context, or you are at a boundary.
- Narrow every
catchwithinstanceofand rethrow what you do not recognize. - Handle expected failures; let bugs surface.
- Chain with
causeinstead of replacing errors. - Log once, at the boundary, including the cause chain.
- Keep
tryblocks small. - Await, return, or
.catch()every promise. - Use
finallyfor cleanup even when you do not catch. - Treat global handlers as a last resort for logging and shutdown.
Exercise
A repository function saveOrder catches every database error, logs it with console.error, and returns false. The HTTP handler checks the return value and sends a 500 if it is false. Name two problems with this design and describe a better split of responsibilities.
Show answer
First, the boolean throws away the error: the handler cannot tell a constraint violation (an expected failure, perhaps a 409) from a connection outage or a bug, and the cause is lost. Second, logging in the repository means that if callers also log, one failure is logged more than once, and non-HTTP callers cannot choose how to report it. Better: saveOrder throws. It can convert known database errors into custom classes such as DuplicateOrderError and wrap the rest with { cause }. The HTTP handler, the boundary, uses instanceof to map known errors to status codes, and logs only unexpected ones, once, with the full cause chain.
Exercise
Why is it risky to put an entire 40-line function body inside one try block whose catch returns a default value?
Show answer
The catch will also intercept errors from lines that were never expected to fail, including bugs such as a TypeError from a typo. Those bugs are then silently turned into the default value instead of surfacing. Keeping the try around only the operation expected to fail, and rethrowing unrecognized error types, keeps bugs visible.
Exercise
In the handleRequest example, why does the 404 branch return without calling logError, while the 500 branch logs?
Show answer
A missing user is an expected outcome of normal use, so it is answered with a 404 and does not need an error log entry (at most a metric). The 500 branch handles unexpected errors, which may be bugs or outages, so the boundary logs them once with their cause chain so someone can investigate.