Sub topic 13
Logging and Serializing Errors with Their Causes
This chapter assumes you already know how to write custom error classes with name and structured fields, how the cause option works, and how to walk a cause chain. It also assumes you know that cause is an own, non-enumerable property. Here those pieces come together on a practical problem: turning an error, with everything attached to it, into data that a log line, a JSON file, or a monitoring service can store.
Why JSON.stringify Loses Most of an Error
The most common logging mistake is to pass an error straight to JSON.stringify:
const err = new Error('Disk full', { cause: new Error('ENOSPC') });
console.log(JSON.stringify(err)); // '{}'The output is an empty object because JSON.stringify only includes own, enumerable, string-keyed properties. None of the standard error fields meet that rule:
| Property | Where it lives | Enumerable | Included by JSON.stringify |
|---|---|---|---|
| `message` | Own property, set by the constructor | No | No |
| `stack` | Own property (V8, SpiderMonkey) or accessor | No | No |
| `cause` | Own property, only if the option was given | No | No |
| `name` (built-in errors) | Inherited from the prototype | No | No |
| `name` set with `this.name = ...` | Own property | Yes | Yes |
| Custom fields such as `status` | Own property | Yes | Yes |
The last two rows are easy to miss. A custom class that assigns this.name in its constructor creates an own, enumerable name, so that field does survive:
class HttpError extends Error {
constructor(status, message, options) {
super(message, options);
this.name = 'HttpError';
this.status = status;
}
}
const err = new HttpError(503, 'Upstream unavailable', { cause: new Error('ECONNRESET') });
console.log(JSON.stringify(err)); // '{"name":"HttpError","status":503}'The message, stack, and the whole cause chain are gone. A log that says only {"name":"HttpError","status":503} tells you that something failed but not what failed or why.
A Serializer That Follows the Cause Chain
The fix is to copy the non-enumerable fields explicitly and to recurse into cause. A version you can rely on in production also needs to handle a few edge cases:
- Cycles. Code can set
a.cause = b; b.cause = a, and naive recursion would never end. - Deep chains. A retry loop that wraps on every attempt can build a chain hundreds of levels deep.
- Non-Error causes.
causecan hold any value, such as a string, a status object, ornull. AggregateError. Itserrorsarray is own but non-enumerable, so it needs the same explicit copy.- Stack size. Stacks are large, and you may want to leave them out of some outputs.
function serializeError(value, options = {}) {
const { maxDepth = 10, includeStack = true } = options;
const seen = new WeakSet();
function walk(v, depth) {
if (!(v instanceof Error)) return v;
if (seen.has(v)) return '[Circular]';
if (depth >= maxDepth) return '[MaxDepth]';
seen.add(v);
const out = { ...v, name: v.name, message: v.message };
if (includeStack) out.stack = v.stack;
if ('cause' in v) out.cause = walk(v.cause, depth + 1);
if (v instanceof AggregateError) {
out.errors = v.errors.map((e) => walk(e, depth + 1));
}
return out;
}
return walk(value, 0);
}Here is what each part does:
- The spread
{ ...v }copies own enumerable fields first, so custom data likestatus,code, oruserIdis kept without the serializer having to know about it. nameandmessageare copied explicitly.nameis often inherited from the prototype, andmessageis non-enumerable.- The
'cause' in vcheck keeps the difference between "no cause" and "cause was explicitlyundefined".JSON.stringifydropsundefinedvalues anyway, but other targets, such asutil.inspector a structured logger, may show the difference. - The
WeakSetstops infinite recursion. It also turns a repeated error into'[Circular]', for example when the same error object appears twice inside oneAggregateError. For logging, that trade-off is usually fine.
Applied to the earlier example:
console.log(JSON.stringify(serializeError(err, { includeStack: false }), null, 2));{
"name": "HttpError",
"status": 503,
"message": "Upstream unavailable",
"cause": {
"name": "Error",
"message": "ECONNRESET"
}
}Remaining edge cases
The serializer returns non-Error causes unchanged, and that can still cause problems in JSON.stringify. A cause that holds a BigInt throws a TypeError. A plain object with a cycle throws too. A plain object that contains an Error nested inside it serializes that inner error as {} again. If your code produces causes like these, either normalize them where they are thrown or wrap the final JSON.stringify call in a try/catch with a fallback such as String(err).
Putting toJSON on Your Base Class
JSON.stringify calls a toJSON method if the object has one. Adding toJSON to your own base error class makes every subclass serialize correctly:
class AppError extends Error {
constructor(message, options) {
super(message, options);
this.name = new.target.name;
}
toJSON() {
return serializeError(this);
}
}
class PaymentError extends AppError {}
const e = new PaymentError('Card declined', { cause: new Error('insufficient_funds') });
console.log(JSON.parse(JSON.stringify(e)).cause.message); // 'insufficient_funds'This approach has a limit. It covers only your own classes. A TypeError thrown by the runtime, or an error from a third-party library, still serializes as {}. For that reason, the main fix belongs at the logging boundary: call serializeError on every caught value before you log it. Treat toJSON as a convenience on top of that.
What Consoles and Loggers Already Do
You often don't need a serializer just to look at an error during development. In recent Node.js versions, console.log(err) uses util.inspect, which prints the stack, enumerable custom fields, and the cause chain with a [cause]: marker for each level. Browser devtools also show a cause, but the format differs from browser to browser.
The problem starts when the output is machine-read. Structured loggers turn the error into JSON, and each library has its own rules for doing that. Some follow cause. Others fold the cause into the stack text or drop it entirely. Before you trust a logger, throw an error with a two-level cause chain in a test and check what reaches your log store.
Logs Versus Responses: Redacting What You Send
A full serialization belongs in your server logs. It does not belong in an HTTP response. Stack traces show file paths and library versions. Causes can contain SQL text, hostnames, or user data that a lower layer put into its message. The spread in serializeError also copies every enumerable field, including ones you may not want to expose.
Keep two separate outputs:
function toPublicError(err) {
const status = err instanceof HttpError ? err.status : 500;
return {
status,
body: {
error: err instanceof HttpError ? err.name : 'InternalError',
message: status < 500 ? err.message : 'Something went wrong',
},
};
}
function handleFailure(err, logger, res) {
logger.error({ err: serializeError(err) }, 'request failed');
const { status, body } = toPublicError(err);
res.statusCode = status;
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify(body));
}The log gets the full chain. The client gets only the parts you chose on purpose. The response body never includes the cause.
Deserializing: What You Cannot Get Back
Serialized errors sometimes cross a process boundary, for example from a worker to a main process or from one service to another. Parsing the JSON gives back a plain object, not an error. It has no prototype chain, so instanceof checks fail and the stack refers to the other process. If the receiver needs to branch on the error type, map name to a known class and rebuild it:
const registry = { HttpError, PaymentError };
function deserializeError(data) {
if (data === null || typeof data !== 'object' || typeof data.message !== 'string') {
return data;
}
const { name, message, stack, cause, ...fields } = data;
const options = 'cause' in data ? { cause: deserializeError(cause) } : undefined;
const err = new Error(message, options);
if (Object.hasOwn(registry, name)) Object.setPrototypeOf(err, registry[name].prototype);
err.name = name;
Object.assign(err, fields);
if (stack) err.stack = stack;
return err;
}This function deliberately does not call the subclass constructors, because their signatures differ. HttpError takes a status first, and other classes take other arguments. Building a plain Error and then setting its prototype avoids that problem. The Object.hasOwn check on the registry stops a payload from naming constructor or __proto__ and picking up a prototype you never meant to allow. Treat incoming error data like any other untrusted input.
Exercise
A teammate logs errors with logger.info(JSON.stringify({ err })). For a plain new Error('timeout', { cause: someError }), what does the err field contain, and why?
Show answer
It contains {}. message and stack are own but non-enumerable, cause is own but non-enumerable, and name is inherited from Error.prototype. JSON.stringify only includes own enumerable properties, so nothing is left. Passing serializeError(err) instead fixes it.
Exercise
Why does serializeError use a WeakSet and a maxDepth limit, when a well-behaved cause chain is a finite list?
Show answer
cause is a writable property that any code can set, so a cycle (a.cause = b; b.cause = a) is possible and would make the recursion run until the stack overflows. Even without a cycle, repeated wrapping, for example in a retry loop, can create very deep chains that produce huge log entries. The WeakSet detects cycles and repeated objects, and maxDepth limits output size.
Exercise
You add toJSON to your AppError base class. Is that enough to make every error in your service log correctly? Explain.
Show answer
No. toJSON runs only for instances of your own classes. Errors thrown by the runtime (TypeError, RangeError), by Node.js APIs, or by third-party libraries still serialize as {} or close to it. You still need to call a general serializer such as serializeError at the logging boundary for every caught value.