Sub topic 9
Wrapping Errors at Layer Boundaries
This chapter assumes you know how to define a custom error class with a proper name, how to tell errors apart with instanceof, and how the cause option of the Error constructor works.
Why wrap at a boundary
Most programs are built in layers: a route handler calls a service, the service calls a data module, and the data module calls the file system or a database. Each layer understands failures in its own terms. An ENOENT from readFile or a SyntaxError from JSON.parse tells the caller what broke. It does not tell the caller what the program was trying to do.
Wrapping fixes this. You catch the low-level error where it leaves your module, then throw a new error that describes the failed operation. You pass the original as cause, so nobody loses the detail.
A worked example
Save this as config.mjs and run it with node config.mjs. The .mjs extension turns on ES modules, which allows top-level await.
import { readFile } from 'node:fs/promises';
class ConfigError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'ConfigError';
}
}
async function loadConfig(path) {
let text;
try {
text = await readFile(path, 'utf8');
} catch (err) {
throw new ConfigError(`Cannot read config file ${path}`, { cause: err });
}
try {
return JSON.parse(text);
} catch (err) {
throw new ConfigError(`Config file ${path} is not valid JSON`, { cause: err });
}
}
try {
await loadConfig('./missing.json');
} catch (err) {
console.log(err.name); // 'ConfigError'
console.log(err.message); // 'Cannot read config file ./missing.json'
console.log(err.cause.code); // 'ENOENT'
}The example uses two separate try blocks so that each message names the step that failed. Callers only need to catch ConfigError. Anyone debugging can still read err.cause.
Common mistakes
Wrapping your own errors twice
If a large try block contains code that already throws a ConfigError, a blanket catch wraps it again and buries the useful message one level deeper. Pass your own errors through unchanged:
function wrapAsConfigError(err, message) {
if (err instanceof ConfigError) return err;
return new ConfigError(message, { cause: err });
}Inside a catch, write throw wrapAsConfigError(err, 'Failed to load config').
Dropping the cause
Writing throw new ConfigError(err.message) copies the text but throws away the original stack, the code property, and any other fields. Always pass { cause: err }.
Wrapping programmer bugs
A TypeError from a typo in your own code is not a config failure. If you wrap it as one, the bug looks like an environment problem. Catch narrowly, and wrap only the operations whose failures you expect.
Wrapping inside a layer
Wrap once, at the point where the error leaves a module. If every function in between also wraps, the chain gets long and repeats itself.
| Situation | Action |
|---|---|
| Low-level error leaving your module | Wrap with a domain error and `cause` |
| Error is already your module's type | Rethrow unchanged |
| Unexpected bug (`TypeError`, `ReferenceError`) | Let it propagate |
| Caller can recover and needs no detail | Handle it; don't throw |
Exercise
A function saveUser contains one try block that calls validate(user), which can throw a UserError, and then db.insert(user), which can throw a driver error. The catch block always does throw new UserError('Save failed', { cause: err }). What goes wrong, and how do you fix it?
Show answer
When validation fails, the useful UserError (for example "Email is required") gets wrapped in a second UserError, so the caller sees "Save failed" and has to dig into cause to find the real message. Fix it by rethrowing UserError instances unchanged (if (err instanceof UserError) throw err;) or by moving validate outside the try block. That way only the driver error gets wrapped.