Sub topic 14
Where to Catch, Log, or Let Errors Propagate
This chapter assumes you know how try/catch works, how to check a caught error with instanceof and rethrow it, how to wrap an error with cause, and how global handlers work. Those tools are covered in earlier chapters. This chapter is about deciding where in your code to use each of them.
The core rule: catch only where you can act
A catch block is useful only if it does something about the error. If the code at that point cannot do anything about it, leave the error alone and let it propagate, meaning it travels up the call stack to a caller that can handle it.
A catch is worth writing when it does one of these things:
- Recovers. It supplies a default value, retries, or takes a fallback path.
- Adds context. It wraps the error with
causeso the message says what the code was trying to do. - Translates. It turns an internal error into something the caller understands, such as an HTTP status or a message for the user.
- Cleans up. It releases a resource. A
finallyblock is usually a better fit for this.
Any other catch adds noise, or it hides failures.
Handle errors at boundaries
A boundary is a point where control passes from your code to something outside it. Examples are an HTTP request handler, a UI event listener, a queue consumer, or a script's main function. A boundary is where you log the error and turn it into a response. The layers below the boundary mostly let errors pass through.
class NotFoundError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'NotFoundError';
}
}
const users = new Map([[1, { id: 1, name: 'Ada' }]]);
function findUser(id) {
const user = users.get(id);
if (!user) throw new NotFoundError(`User ${id} not found`);
return user;
}
function getGreeting(id) {
// No try/catch: this layer can't fix a missing user, so errors propagate.
const user = findUser(id);
return `Hello, ${user.name}!`;
}
function handleRequest(id) {
// Boundary: translate known errors, log unexpected ones once.
try {
return { status: 200, body: getGreeting(id) };
} catch (err) {
if (err instanceof NotFoundError) {
return { status: 404, body: err.message };
}
console.error('Unexpected error:', err);
return { status: 500, body: 'Internal error' };
}
}
console.log(handleRequest(1)); // { status: 200, body: 'Hello, Ada!' }
console.log(handleRequest(2)); // { status: 404, body: 'User 2 not found' }getGreeting contains no error handling. That is correct, because it has nothing useful to add. The boundary handles the error it expects, a missing user, with a 404 and no log entry. Anything else is treated as a bug: it gets logged and becomes a 500 response.
Log once
When every layer logs and then rethrows, one failure shows up as several log entries. That makes incidents harder to read. Log at the point where the error stops propagating, which is the boundary or the global handler. If an inner layer has information the boundary lacks, add it to the error with cause rather than logging it there.
Common mistakes
| Mistake | Problem | Better approach |
|---|---|---|
| Catch, log, and rethrow in every layer | The same failure is logged several times | Log once at the boundary |
| Empty `catch` | The failure is hidden | Handle it, rethrow it, or document why it is ignored |
| Catch everything and treat it as expected | Bugs look like normal outcomes | Check the type with `instanceof` and rethrow unknown errors |
| Rely only on global handlers | No chance to recover or return a useful response | Handle errors at boundaries and keep global handlers as the last resort |
| Wrap an error without `cause` | The original stack trace is lost | Pass `{ cause: err }` |
Expected errors versus bugs
Expected failures include invalid input, a missing record, or a network timeout. These are part of normal operation, so give them their own error classes and handle them on purpose. Bugs include a TypeError from reading a property of undefined. Don't try to recover from bugs in local catch blocks. Let them reach the boundary, where they get logged and become a generic failure response.
Exercise
A function readSettings() calls fs.readFileSync and then JSON.parse. When the file is missing, the app should use default settings. When the file contains invalid JSON, a developer should be able to find out which file was broken. Where should each error be handled?
Show answer
Catch the missing-file error (code 'ENOENT') inside readSettings and return the defaults, because the function can recover from it there. Do not recover from the JSON SyntaxError. Wrap it in a new Error that names the file path, pass { cause: err } so the original error stays attached, and rethrow it. The boundary or the global handler then logs it once.
Exercise
Why is it a problem when a data layer, a service layer, and a request handler each run console.error(err) and then rethrow?
Show answer
One failure produces three log entries. That makes logs noisy and makes the failure look like three separate problems. Log only where the error stops propagating, and add context with cause in the inner layers.