What the Caller Sees When Something Breaks
You ask an agent for a function that exports a customer's invoices to a CSV file and uploads it, so the customer can download it later. It hands you this, and it runs cleanly the first time you try it:
import { mkdtemp, open, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
export async function exportInvoices(customerId: string, store: Store, lock: Lock): Promise<string | null> {
await lock.acquire();
const dir = await mkdtemp(join(tmpdir(), "export-"));
const path = join(dir, "invoices.csv");
const file = await open(path, "w");
try {
const invoices = await loadInvoices(customerId);
for (const inv of invoices) {
// writeFile writes the whole string; a bare write() may write only part of it.
await file.writeFile(`${inv.id},${inv.totalCents}\n`);
}
await file.close();
const url = await store.upload(path);
await rm(dir, { recursive: true });
lock.release();
return url;
} catch (err) {
log.error(`export failed: ${(err as Error).message}`);
return null;
}
}It looks careful. There is a lock so two exports don't collide, a temporary file, a try block and a log line. Each of those pieces goes wrong the moment something fails, and none of it shows up while the database and the storage service are healthy. The code you get from an agent is usually tested on the path where everything works. Your job is to read the other paths.
A function has more than one exit
Every function ends in one of a small number of ways. It returns a value, or it throws, or it never returns because it hangs or the process dies. Each line that can fail opens another path to one of those endings. Reading error handling means walking each path and writing down two things: what the caller receives, and what state the world is left in.
Take the function above and list the lines that can fail. loadInvoices talks to a database, so it can time out. file.write can fail if the disk is full. store.upload crosses a network, so it can time out or get a 503. mkdtemp and open can fail too. Now walk each one.

lock.acquire() leaves the lock held, and the two inside the try also leave the export file on disk. Only the path where nothing fails cleans up.If loadInvoices throws, control jumps to the catch block. The caller gets null. The file handle was opened and never closed, and the file and its directory were never removed, so they stay on disk. The lock was acquired and never released, so the next export, for any customer, waits forever on lock.acquire().
If store.upload throws, the same thing happens, with one addition. The file on disk now contains a full list of that customer's invoice IDs and totals. mkdtemp creates its directory readable only by the current user, but nothing will ever delete it, so a sensitive export sits in the temp directory indefinitely. One network timeout has left that file behind and stopped every later export.
If mkdtemp or open throws, it happens before the try, so the error goes straight to the caller. That part is fine. The lock, though, was taken on the line above, so it leaks here too.
Only one path, the one where nothing fails, releases the lock and deletes the file. That is the cleanup mistake from the list above: release written as the last few lines of the happy path instead of something that runs on every exit.
The handler that turns failure into success
Look at what the caller does with the result. Somewhere upstream there is probably a line like this:
const url = await exportInvoices(customer.id, store, exportLock);
await sendEmail(customer.email, `Your export is ready: ${url}`);When the export fails, the customer gets an email that says "Your export is ready: null". The job that called this records a success. Your monitoring sees no exception. The only trace is one log line among thousands, and it says export failed: timed out. The return type did admit that null could come back, but a template string accepts null without complaint, and a null carries no reason.
This is the catch-all handler: catch every error, log it, return a default. Agents produce this shape often, because it makes the code look defended and it never crashes in a demo. What it actually does is convert a loud failure into a quiet wrong answer. A crash is easy to find because it tells you where it happened. A null that flows three functions downstream before anything notices is hard to find, and by then the stack trace that would have explained it is gone.
You can watch both versions fail. This playground fakes the disk, the lock and a storage service that times out, then runs the agent's shape and a fixed one against them:
class Lock {
held = false;
private waiting: (() => void)[] = [];
async acquire() {
while (this.held) await new Promise<void>((wake) => this.waiting.push(wake));
this.held = true;
}
release() {
this.held = false;
this.waiting.shift()?.();
}
}
class ExportError extends Error {
name = "ExportError";
}
const disk = new Set<string>();
let fileCount = 0;
const createTempFile = () => {
const path = `/tmp/export-${++fileCount}.csv`;
disk.add(path);
return path;
};
const upload = async (path: string): Promise<string> => {
await new Promise((r) => setTimeout(r, 20));
throw new Error("timed out");
};
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const agentLock = new Lock();
async function exportLikeTheAgent(customerId: string): Promise<string | null> {
await agentLock.acquire();
const path = createTempFile();
try {
const url = await upload(path);
disk.delete(path);
agentLock.release();
return url;
} catch (err) {
return null; // the agent's version logs here and carries on
}
}
const fixedLock = new Lock();
async function exportFixed(customerId: string): Promise<string> {
await fixedLock.acquire();
try {
const path = createTempFile();
try {
return await upload(path);
} catch (err) {
throw new ExportError(`uploading invoice export for customer ${customerId}`, { cause: err });
} finally {
disk.delete(path);
}
} finally {
fixedLock.release();
}
}
const url = await exportLikeTheAgent("c_42");
console.log("agent's version, email says:", `Your export is ready: ${url}`);
console.log(" files left on disk:", [...disk], "lock held:", agentLock.held);
const next = await Promise.race([exportLikeTheAgent("c_43").then(() => "finished"), sleep(200).then(() => "still waiting for the lock")]);
console.log(" next customer's export:", next);
disk.clear();
try {
await exportFixed("c_42");
} catch (err) {
const e = err as ExportError;
console.log("fixed version, caller catches:", `${e.name}: ${e.message}`, "| cause:", (e.cause as Error).message);
}
console.log(" files left on disk:", [...disk], "lock held:", fixedLock.held);Output
To fix a handler like the agent's, take each error it catches and ask what the caller should do differently when it happens. If the answer is "it should know the export failed", then the handler has to tell it. Returning null here lets the caller carry on as if the export worked. The function should throw, or return a result whose failure case the caller is forced to handle.
Some languages make the failure part of the return type, which makes this mistake harder to write. In Go a function returns (url string, err error), so the error sits in the signature next to the URL. Assigning the URL while discarding the error takes a visible url, _ := export(), which a reviewer can spot, though Go also lets you call export() as a bare statement and drop both results. In Rust it returns Result<Url, ExportError>, and the compiler won't let you reach the URL until you decide what happens in the error case, even if the decision is unwrap(). In TypeScript, nothing in Promise<string> says the promise can reject, so the discipline has to come from you. You can get Rust's guarantee with a union type:
type ExportResult =
| { ok: true; url: string }
| { ok: false; error: ExportError };
const result = await exportInvoices(customer.id, store, exportLock);
if (!result.ok) return reportFailure(customer, result.error);
await sendEmail(customer.email, `Your export is ready: ${result.url}`);Reading result.url before checking result.ok is a compile error, because the failure case has no url. Whatever the language, a function that can fail should say so in a way the caller cannot mistake for success.
Errors that say nothing
The second problem with that handler is the message. export failed: timed out does not say which customer, which step, or what timed out. When the agent does rethrow, it often does something like this:
try {
return await store.upload(path);
} catch {
throw new Error("export failed");
}That stops the silent success and throws away the explanation. The new message names no customer and no step, and the original timeout is gone completely, because a new Error keeps nothing of the one that was caught unless you hand it over. Python differs here: it keeps the original as __context__ and prints both in the traceback, though str(e) still holds only the new message. The fix is to add what you were doing and on which input, and attach the original as the cause:
class ExportError extends Error {
name = "ExportError";
}
try {
return await store.upload(path);
} catch (err) {
throw new ExportError(`uploading invoice export for customer ${customerId}`, { cause: err });
}Node and Bun print the whole chain when they log an error with a cause, and code that needs the timeout can still reach it as err.cause. Python does the same thing with raise ExportError(...) from e, and Go with fmt.Errorf("uploading export for customer %d: %w", id, err), where errors.Is and errors.As can still find the wrapped error.
A good error message answers three questions for the person reading it at 3 a.m.: what was being attempted, on what input, and what went wrong underneath. Be careful with the second one. The customer ID is fine to include. A password, an API key, a full card number or a session token must never go into an error message, because error messages end up in logs, and logs are read by more people and kept longer than the data they describe.
Where each error belongs
Once you stop catching everything, you need a rule for what to catch. Every error condition belongs in one of three places.
Handle it locally when this code has a specific, correct response that makes the operation succeed anyway. A timeout on an idempotent read can be retried a bounded number of times. A missing optional config file can mean "use the defaults", if that is a deliberate decision. A cache miss means go to the database. In each case you can name the recovery.

Propagate it when the caller is the one who can decide. "Customer not found" means something different to an admin screen than to a nightly batch job, so the export function should throw and let each caller choose. Most errors belong here. Propagating is the default, and you add context on the way up.
Crash when the program has reached a state that should be impossible. An invoice with a negative total, a customer ID that is undefined after it was validated, a required database URL missing at startup: these are bugs or broken deployments. Continuing means working with data you already know is wrong, and every write after that point spreads the damage. Stopping gives you a stack trace at the exact place the problem started, and a supervisor (systemd, Kubernetes, your job runner) can restart the process cleanly. In a web server, crashing usually means the request fails with a 500 and an alert fires, while the server keeps serving other requests. In a batch job or worker, it means the process exits. Either way, nothing downstream runs on the bad data.
For the invoice export, sorted:
| Condition | Where it goes | Why |
|---|---|---|
| Storage upload times out once | Handle: retry up to 3 times with backoff | Uploading the same file to the same key twice is harmless |
| Storage still failing after retries | Propagate with context | The caller decides whether to tell the customer or requeue |
| Customer has no invoices | Handle: upload an empty CSV | This is a normal case, and the customer expects a file |
| Customer does not exist | Propagate | Only the caller knows whether this is a user error or a bug |
| An invoice total is negative | Crash | The data is corrupt; exporting it spreads the corruption |
For that last row, write the check as an explicit if that throws. console.assert only logs a message and lets the function carry on, so it cannot guard anything that has to hold in production.
if (inv.totalCents < 0) {
throw new InvariantViolation(`invoice ${inv.id} has negative total ${inv.totalCents}`);
}Cleanup that runs on every path
Now fix the leaks. The rule is that every resource you acquire has exactly one release, and that release is attached to the acquisition so it runs no matter how the block exits. Languages give you a construct for this. JavaScript has finally, and TypeScript 5.2 added using declarations that release a resource when its block ends. Python has with, Go has defer, Java has try-with-resources, C# has using, and Rust releases resources when their owner goes out of scope.
export async function exportInvoices(customerId: string, store: Store, lock: Lock): Promise<string> {
await lock.acquire();
try {
const dir = await mkdtemp(join(tmpdir(), "export-"));
try {
const path = join(dir, "invoices.csv");
await writeCsv(path, await loadInvoices(customerId));
try {
return await store.upload(path);
} catch (err) {
throw new ExportError(`uploading invoice export for customer ${customerId}`, { cause: err });
}
} finally {
await rm(dir, { recursive: true, force: true }).catch((err) =>
log.warn(`could not remove ${dir}`, err),
);
}
} finally {
lock.release();
}
}
async function writeCsv(path: string, invoices: Invoice[]): Promise<void> {
const file = await open(path, "w");
try {
for (const inv of invoices) {
if (inv.totalCents < 0) {
throw new InvariantViolation(`invoice ${inv.id} has negative total`);
}
// writeFile writes the whole string; a bare write() may write only part of it.
await file.writeFile(`${inv.id},${inv.totalCents}\n`);
}
} finally {
await file.close();
}
}Each resource gets its own try right after the line that acquires it, and its own finally. Walk the paths again. If loadInvoices throws, no file is open yet, the finally deletes the directory, the outer finally releases the lock, and the error reaches the caller unchanged. If a write fails, writeCsv closes the file before the same cleanup runs.
The .catch on rm is there for a reason. An error thrown inside a finally replaces the one already on its way out, so if removing the directory failed, the caller would get that error and the export error would be lost. Catching and logging the cleanup failure keeps the export error primary. If the upload fails, the caller gets an ExportError that names the customer and carries the storage error as its cause. The retry is left out to keep the example short; it would go in a small helper around store.upload.
The await in return await store.upload(path) matters too. Without it, the function returns the pending upload as it is: the catch never sees its failure, and the finally deletes the file while the upload may still be reading it.
const disk = new Set<string>();
const upload = async (path: string): Promise<string> => {
await new Promise((r) => setTimeout(r, 20)); // the upload opens the file a moment later
if (!disk.has(path)) throw new Error(`ENOENT: no such file ${path}`);
return "https://files.example.com/export-1.csv";
};
async function exportWith(awaitUpload: boolean): Promise<string> {
const path = "/tmp/export-1.csv";
disk.add(path);
try {
return awaitUpload ? await upload(path) : upload(path);
} catch (err) {
throw new Error(`uploading invoice export for customer c_42`, { cause: err });
} finally {
disk.delete(path);
}
}
for (const awaitUpload of [false, true]) {
const label = awaitUpload ? "return await upload()" : "return upload() ";
try {
console.log(label, "->", await exportWith(awaitUpload));
} catch (err) {
console.log(label, "-> threw:", (err as Error).message);
}
}Output

await, the finally deletes the file before the upload opens it, and the ENOENT skips the catch. With await, the finally waits and the upload succeeds.The first line shows the bare ENOENT reaching the caller, with no customer named, because the catch was skipped and the file was already gone. The second shows the upload succeeding, because the finally waited for it.
There is no catch-all left in this function. That is deliberate. This function has no general recovery to offer, so it lets errors out and makes sure it cleans up on the way.
Translating at the edge
Errors do get caught eventually, at a boundary: the HTTP handler, the job runner, the CLI's main. That is the place for a broad handler, because that is where someone has to decide what the outside world sees. An HTTP handler maps CustomerNotFound to a 404, ExportError to a 503 with a hint to retry later, and anything unexpected to a 500 with a generic message. The full detail, cause chain and stack trace go to your logs. The client gets a status code and a sentence, never a stack trace, because a stack trace can reveal file paths, library versions and sometimes data.

A broad catch that turns a failure into a response or into silence belongs at a boundary like this, where it translates the error and records it. Deeper in the code, a broad catch that cleans up or adds context and then rethrows is fine. One that swallows the error and returns a default hides it from the one caller who could have done something about it.
When you review error handling, trace each line that can fail to its exit and write down what the caller receives and what is still held open. A path where the caller receives a normal-looking value after a failure, or where a lock, connection or file is still held, is a bug, even if no test has hit it yet.