Sub topic 9
Wrapping Errors at Layer Boundaries
This chapter assumes you know how to define a custom error class with name and structured fields, how to tell errors apart with instanceof, and how the cause option attaches one error to another. It also uses async/await and Node.js ES modules.
A real application has layers. A database driver sits at the bottom, a repository calls the driver, a service holds business rules, and an HTTP handler talks to clients. Each layer speaks its own language. The driver reports ECONNREFUSED. The service cares that "the user could not be loaded". The client should see a status code and a safe message. Wrapping is how an error moves from one language to the next without losing the original details.
Why Wrap Instead of Letting Errors Propagate
If a low-level error travels unchanged to the top, it causes three problems:
- The message lacks context.
Unexpected token } in JSON at position 41does not say which file was being read or why. - Upper layers couple to lower ones. If the HTTP handler checks
err.code === 'ECONNREFUSED', swapping the database driver breaks the handler. - Details leak. Hostnames, SQL fragments, and file paths can end up in a response body.
Wrapping fixes all three. You catch the error at the boundary, throw a new error that describes the failed operation in the current layer's terms, and pass the original as cause. The caller gets a meaningful type and message. Someone debugging still gets the full original error.
import { readFile } from 'node:fs/promises';
async function loadConfig(path) {
try {
const text = await readFile(path, 'utf8');
return JSON.parse(text);
} catch (err) {
throw new Error(`Failed to load config from ${path}`, { cause: err });
}
}
try {
await loadConfig('./missing.json');
} catch (err) {
console.log(err.message); // 'Failed to load config from ./missing.json'
console.log(err.cause.code); // 'ENOENT'
}The outer message describes what the program was trying to do. The cause tells you why it failed. A good wrapped error reads like a short sentence with a reason attached: "Failed to load config, because the file does not exist."
A Layered Example
The program below has four layers. Only two of them catch errors: the repository and the HTTP handler. Save it as layers.mjs and run it with node layers.mjs.
class HttpError extends Error {
constructor(status, message, options) {
super(message, options);
this.name = 'HttpError';
this.status = status;
}
}
class NotFoundError extends HttpError {
constructor(resource, options) {
super(404, `${resource} not found`, options);
this.name = 'NotFoundError';
}
}
class DatabaseError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'DatabaseError';
}
}
// Driver layer: a stand-in for a real database client.
const rows = new Map([[1, { id: 1, email: '[email protected]' }]]);
async function driverQuery(id) {
if (id === 99) {
const err = new Error('connect ECONNREFUSED 10.0.0.5:5432');
err.code = 'ECONNREFUSED';
throw err;
}
return rows.get(id);
}
// Repository layer: translates driver errors into DatabaseError.
async function findUserRow(id) {
try {
return await driverQuery(id);
} catch (err) {
throw new DatabaseError(`Query for user ${id} failed`, { cause: err });
}
}
// Service layer: applies business rules, does not catch.
async function getUser(id) {
const row = await findUserRow(id);
if (row === undefined) throw new NotFoundError(`User ${id}`);
return row;
}
// HTTP layer: maps errors to responses, logs full detail internally.
async function handleGetUser(id) {
try {
const user = await getUser(id);
return { status: 200, body: user };
} catch (err) {
if (err instanceof HttpError) {
return { status: err.status, body: { error: err.message } };
}
console.error('Request failed:', err);
if (err instanceof DatabaseError) {
return { status: 503, body: { error: 'Service temporarily unavailable' } };
}
return { status: 500, body: { error: 'Internal server error' } };
}
}
console.log(await handleGetUser(1)); // { status: 200, body: { id: 1, ... } }
console.log(await handleGetUser(2)); // { status: 404, body: { error: 'User 2 not found' } }
console.log(await handleGetUser(99)); // logs the DatabaseError with its cause, then { status: 503, ... }Look at what each layer knows. The handler never mentions ECONNREFUSED. It only knows about HttpError and DatabaseError. The client never sees the internal IP address. The console.error call still prints the full error, and Node.js prints the cause too, under a [cause] entry.
Choosing What to Do at a Catch Site
A catch block has more options than "handle it" or "wrap it". Pick the one that fits the boundary.
| Action | Code shape | Use when |
|---|---|---|
| Let it propagate | no `try` at all | The function is inside a layer and adds no useful context |
| Rethrow unchanged | `throw err;` | You caught to inspect, clean up, or handle some types, but this one is not yours |
| Wrap with cause | `throw new XError(msg, { cause: err })` | Crossing a layer boundary, or the caller needs to know which operation failed |
| Translate to a domain error | `throw new NotFoundError(...)` | A low-level condition has a clear business meaning, such as a unique-key violation meaning "email already taken" |
| Recover | return a value | You can actually continue, for example by retrying or using a default |
Most functions should be in the first row. Wrapping belongs at the edges of a layer, not in every function.
Common Mistakes
Discarding the original error
// Bad: the original type, stack, and code are gone.
throw new Error(`Failed to load config: ${err.message}`);Copying the message into a string keeps one line of text and throws away the rest. Always pass { cause: err }. You can still include the inner message in the outer one if it helps readers of a single log line. The cause is what keeps the full details.
Re-wrapping errors you already understand
If the repository throws a NotFoundError on purpose, a broad catch in the same function would turn it into DatabaseError: Query failed. That hides the real meaning. Let your own domain errors pass through before you wrap:
async function findUserOrThrow(id) {
try {
const row = await driverQuery(id);
if (row === undefined) throw new NotFoundError(`User ${id}`);
return row;
} catch (err) {
if (err instanceof NotFoundError) throw err;
throw new DatabaseError(`Query for user ${id} failed`, { cause: err });
}
}A cleaner fix is to keep the try narrow, as findUserRow does in the layered example, so it only covers the driver call.
A `try` block that is too wide
When the try covers your own logic as well as the external call, a bug like TypeError: Cannot read properties of undefined gets labelled as a DatabaseError. Someone on call then spends an hour checking the database. Put only the call that can fail for external reasons inside the try.
Forgetting `await` inside `try`
async function findUserRowBroken(id) {
try {
return driverQuery(id); // no await
} catch (err) {
throw new DatabaseError(`Query for user ${id} failed`, { cause: err });
}
}Without await, the function returns the pending promise and leaves the try block before the promise rejects. The rejection skips the catch and reaches the caller as a raw driver error. Use return await inside a try block whenever you mean to catch the rejection.
Wrapping at every level
When each of five functions wraps, you get a five-deep chain like "Failed to handle request → Failed to get user → Failed to find user → Query failed → ECONNREFUSED". Each extra level adds noise without adding information. Wrap where the vocabulary changes, usually once per layer.
Leaking the cause to clients
cause is diagnostic data for operators. The HTTP layer should build response bodies from fields you chose to expose, such as status and a safe message. Never build them from the raw error or its cause. Keep the full chain in server logs.
Exercises
Exercise
A function chargeCard(order) calls a payment SDK inside try { return sdk.charge(order.total); } catch (err) { throw new PaymentError('Charge failed', { cause: err }); }. sdk.charge returns a promise. Sometimes callers receive the SDK's raw error instead of a PaymentError. Why, and how do you fix it?
Show answer
The try block returns the promise without awaiting it, so the function leaves the try before the promise rejects and the catch never runs. Change it to return await sdk.charge(order.total); so the rejection is thrown inside the try and gets wrapped.
Exercise
In the layered example, the repository catches every error from driverQuery and wraps it in DatabaseError. Suppose findUserRow also calls a helper normalizeRow(row) inside the same try, and that helper has a bug that throws a TypeError. What does the HTTP handler return, and what is the better structure?
Show answer
The TypeError is wrapped in a DatabaseError, so the handler returns 503 "Service temporarily unavailable" and the logs point at the database. Move normalizeRow outside the try, so only driverQuery is wrapped. The TypeError then reaches the handler unwrapped and becomes a 500, which correctly signals a bug.
Exercise
A teammate writes catch (err) { throw new Error('Could not save user: ' + err.message); }. Give two pieces of information this loses, and rewrite the line.
Show answer
It loses the original error's type (for example a unique-constraint error class), its stack trace, and any structured fields such as code. Rewrite it as throw new Error('Could not save user', { cause: err });, or use a domain-specific class like new UserSaveError('Could not save user', { cause: err }).