Sub topic 13
Logging and Serializing Errors with Their Causes
This chapter assumes you already know how to write custom error classes with structured fields, how the cause option works, and how to walk a cause chain. Here you will turn an error and its causes into plain data that a JSON logger can store.
Why JSON.stringify Loses Most of an Error
Interactive tools handle errors well. In Node.js, console.log(err) prints the stack, the custom fields, and a nested [cause] section. Structured loggers and HTTP responses are different, because they usually pass objects through JSON.stringify. That function only copies own enumerable properties, which leaves most of an error behind.
| Property | Where it lives | Included by JSON.stringify? |
|---|---|---|
| `message` | Own, non-enumerable | No |
| `stack` | Own, non-enumerable (V8) | No |
| `cause` | Own, non-enumerable | No |
| `name` on a plain `Error` | Inherited from the prototype | No |
| `name` set with `this.name = ...` | Own, enumerable | Yes |
| Custom fields such as `status` | Own, enumerable | Yes |
The result is a log entry that contains your custom fields but no message, no stack, and no root cause.
A Recursive Serializer
The helper below copies the important fields by name and recurses into cause. It also keeps a seen set so that a cycle in the cause chain cannot cause infinite recursion.
class HttpError extends Error {
constructor(status, message, options) {
super(message, options);
this.name = 'HttpError';
this.status = status;
}
}
function serializeError(err, seen = new Set()) {
if (!(err instanceof Error)) return err;
if (seen.has(err)) return '[Circular cause]';
seen.add(err);
return {
...err,
name: err.name,
message: err.message,
stack: err.stack,
cause: serializeError(err.cause, seen),
};
}
const err = new HttpError(503, 'Upstream unavailable', {
cause: new Error('ECONNRESET'),
});
console.log(JSON.stringify(err));
// '{"name":"HttpError","status":503}'
console.log(JSON.stringify(serializeError(err), null, 2));The second log prints an object with name, message, stack, status, and a nested cause object holding the ECONNRESET error.
Some details of how the helper works:
- The spread
...errcopies enumerable custom fields such asstatus. The explicit keys written after it override anything the spread copied. - Non-Error causes such as strings or plain objects are returned unchanged. Any value can be a cause.
- When an error has no cause,
causebecomesundefined, andJSON.stringifydrops the key.
Common Mistakes
- Logging
err.messageonly. This drops the stack and the whole cause chain. When you log a wrapped error, the root failure is usually the part you need. - Returning stacks to clients. Stacks and low-level causes reveal file paths and internals. Serialize everything for your own logs, but send only a safe subset (for example
name,message,status) in HTTP responses. - Ignoring AggregateError. Its
errorsarray is an own enumerable property, so the spread copies it, but the items inside stay as rawErrorobjects that serialize to{}. Map them throughserializeErroras well if you use it.
Exercise
A plain new Error('boom', { cause: 'disk full' }) is passed to JSON.stringify. What is the output, and why?
Show answer
The output is "{}". The message, stack, and cause are own non-enumerable properties, and name is inherited from Error.prototype, so JSON.stringify finds no own enumerable properties to copy.
Exercise
Change serializeError so that each item in an AggregateError's errors array is serialized too.
Show answer
Add a line after the cause line: errors: err instanceof AggregateError ? err.errors.map((e) => serializeError(e, seen)) : undefined,. When the error is not an AggregateError, the key is undefined, so JSON.stringify drops it.