In a Node.js module that wraps low-level failures such as ENOENT or ECONNRESET in its own errors, how do you keep them matchable by code and still diagnosable?
answer
- the code is the contract
- the message is for humans
- keep the original attached
- what inspect prints
- fetch failed hides the reason
basics
~20 sIn Node.js, throw an Error subclass with a stable code of your own and pass the original as cause. Callers match on code, util.inspect prints the cause chain, and retry logic walks cause, as it must for fetch's 'fetch failed'.
solid answer
~40 sFollow Node's own rule: `code` is the contract and `message` is free text. Define an `Error` subclass that sets `name` and a documented `code` such as `SYNC_UPLOAD_FAILED`, and construct it with `{ cause: original }` so the `ENOENT` or `ECONNRESET` survives with its `code`, `syscall` and stack. `util.inspect`, and so `console.log`, prints the `[cause]` chain recursively, giving both layers in one log entry. The cost is that a classifier reading only `err.code` now sees your code, so it must understand your codes or walk `err.cause`. Node 24's global `fetch` does this to you: a network failure rejects with `TypeError: fetch failed`, and the system error, an `AggregateError` or an undici `UND_ERR_*` error sits in `err.cause`.
code
javascript · 25 linesexport class SyncError extends Error {
constructor(code, message, options) {
super(message, options); // options = { cause } keeps the original attached
this.name = 'SyncError';
this.code = code; // stable, documented, matched by callers
}
}
export function findCode(err, wanted, depth = 5) {
for (let e = err; e && depth > 0; e = e.cause, depth--) {
if (wanted.has(e.code)) return e.code;
const inner = Array.isArray(e.errors) && e.errors.find((x) => wanted.has(x?.code));
if (inner) return inner.code;
}
return undefined;
}
export async function upload(url, body) {
try {
return await fetch(url, { method: 'PUT', body });
} catch (err) {
// err is TypeError: fetch failed; the network error is in err.cause
throw new SyncError('SYNC_UPLOAD_FAILED', `upload to ${new URL(url).host} failed`, { cause: err });
}
}go deeper
Recall that new Error(message, { cause }) keeps the original error attached, and that callers should compare a code property, not message text.
Explain building an Error subclass with name and a stable code, and what console.log shows for a chained error compared with JSON.stringify.
Show the production traps: retry checks that miss codes hidden in cause, fetch's 'fetch failed' wrapper, AggregateError links and loggers that serialise errors to almost nothing.
Treat a module's error codes as public API: documented, versioned like Node's own, and classified once, so retry and alert rules do not drift across services.
## Why wrap at all A file-sync module sits between its callers and Node's I/O. When `fs.open` fails with `ENOENT` or an upload fails with `ECONNRESET`, the raw error says **what the operating system refused** but not **what your module was trying to do**: which file, which sync job, which step. Wrapping adds that layer of meaning. Done badly, it destroys the information the caller needs, the original `code`, `syscall`, `path` and stack. Done well, it keeps both. ## The shape Node itself uses Node's own errors set the pattern to copy: - **`code` is the contract.** Node's errors documentation says `error.code` is the most stable way to identify an error and only changes between major versions. - **`message` is for humans.** The same page says message strings may change in any version. Callers must never parse them. - **`name` identifies the class** in logs and stack headers. - **`cause` carries the original.** `new Error(message, { cause })` sets `error.cause` (documented since Node 16.9.0); the constructor leaves it unset when the option is absent. ## Building the wrapper 1. Define one `Error` subclass per module, or a small family, and set `this.name` so stack headers read `SyncError: ...` instead of `Error: ...`. 2. Give every failure a **stable, documented `code` of your own**, such as `SYNC_SOURCE_MISSING` or `SYNC_UPLOAD_FAILED`. Treat the list as public API: renaming a code is a breaking change, exactly as Node treats its own. 3. Pass the original as **`{ cause: err }`**, untouched. Do not copy its message into yours and drop the object: that loses `code`, `syscall`, `path` and the original stack. 4. Put the module-level context, the job or file, in the new message or in extra properties, never by mutating the original error. ## Reading the chain - **`util.inspect` prints the chain.** The errors page says it recursively serialises `error.cause`, so `console.log(err)` shows your stack, then a nested `[cause]` block with the original's stack and its properties such as `code: 'ECONNRESET'`. - **`JSON.stringify(err)` does not.** It keeps only own enumerable properties, so a wrapper with an assigned `code` serialises as `{"code":"SYNC_UPLOAD_FAILED"}`: no message, no stack, no cause. Structured loggers need an explicit serializer for errors. - **Classifiers must walk `cause`.** Once you wrap, a retry check that reads only `err.code` sees your code, not `ECONNRESET`. Either encode retryability in your own codes, or walk `err.cause` with a depth limit, also looking inside an `errors` array when a link is an `AggregateError`. ## Node wraps errors too Several Node APIs hand you an outer error with the real reason inside it, and a classifier that ignores the nesting misreads them: | API | Outer error | Where the reason is | |---|---|---| | global `fetch` on a network failure | `TypeError: fetch failed` | `err.cause`: a system error, an `AggregateError`, or an undici error with a `UND_ERR_*` code | | `net.connect` with family autoselection, all addresses failed | `AggregateError` | `err.errors`, one entry per attempt | | `fs.readFile`, `fs.writeFile` callbacks when closing the file also fails | `AggregateError` | `err.errors`: the operation's error, then the close error | | `util.callbackify` of a promise rejected with a falsy value | `Error` with code `ERR_FALSY_VALUE_REJECTION` | `err.reason` | The `fetch` case catches many teams: code written for `http.request`, where `err.code` is `ECONNRESET` directly, silently stops retrying after a move to `fetch`, because `err.code` on the `TypeError` is `undefined`. ## Deciding retryability once Wrapping moves the retry decision. Before, a caller could read `ECONNRESET` directly; after, it reads `SYNC_UPLOAD_FAILED`. Pick one of two designs and keep to it: - **Classify at the wrap site.** The module inspects the original, walking `cause` and `errors` as needed, and emits distinct codes, say `SYNC_UPLOAD_RETRYABLE` versus `SYNC_UPLOAD_REJECTED`. Callers never look inside. - **Classify at the caller.** The module keeps one code and promises that `cause` holds the original; callers run a shared helper that walks the chain. Mixing the two is how one service retries a failure that its neighbour treats as permanent. ## Mistakes to avoid - Wrapping with `new Error(err.message)`, which keeps the words and loses everything a program can act on. - Matching on the wrapper's message in tests, which locks the wording into the contract. - Unbounded cause walking; a hostile or buggy cycle in `cause` would loop forever without a depth limit. - Wrapping at every layer, so the same failure carries five near-identical messages; wrap where the meaning changes.
- Your retry policy keyed on err.code === 'ECONNRESET' stopped firing after the service moved from http.request to global fetch. Why?With `http.request` the socket's system error reaches you directly, so `err.code` is `ECONNRESET`. `fetch` rejects with `TypeError: fetch failed` and puts the underlying failure in `err.cause`, so the outer `code` is `undefined`. The classifier has to walk `err.cause`, and look inside `errors` when the cause is an `AggregateError`.
- Why does a structured logger often record a wrapped Node error as almost nothing?Loggers that call `JSON.stringify` see only own enumerable properties. `message` and `stack` are not enumerable and neither is `cause` as the constructor installs it, so a wrapper serialises as just `{"code": ...}`. Use the logger's error serializer, or build the object explicitly from `name`, `code`, `message`, `stack` and the cause chain.
Wrapping with cause is like forwarding an email with the original attached instead of retyping it: your cover note says what failed at your layer, and the original, headers and all, is still there for whoever needs it.
- Wrap with new Error(err.message); the text is all that matters.
- Callers should match a custom error by its message wording.
- JSON.stringify(err) records the message, stack and cause chain.
- A fetch network failure has its system code on err.code.
- Node prints error.cause only when showHidden is enabled.
Assumes Node.js 24, where global fetch has been stable since v21 and rejects network failures as TypeError 'fetch failed' with the reason in cause; error.cause is documented since v16.9.0.