JavaScriptFundamental (ES6), part 2
Serialize an Error to JSON in JavaScript
42 An Error does not survive JSON
fairStringify an error and see what arrives. Work out which of its fields are enumerable, then write the projection that actually carries a failure — name, message and cause chain — and confirm what comes back is no longer an Error.
Stuck? Three hints, smallest first
- 1.
messageandstackare not enumerable own properties, soJSON.stringifycannot see them. - 2. Fields you assign yourself are enumerable, which is why some of the object survives and the important part does not.
- 3. Recurse down
causewhile it is still anError, and build a plain object at each level.
const failure = new Error('yaba till timed out', { cause: new Error('ECONNRESET') });
failure.till = 'yaba';
failure.retryable = true;
const naive = JSON.stringify(failure);
const insideAReport = JSON.stringify({ status: 'failed', error: failure });
const enumerability = [failure.propertyIsEnumerable('message'), failure.propertyIsEnumerable('till')];
const spreadKeys = Object.keys({ ...failure });
function toPlain(err) {
const out = { name: err.name, message: err.message };
if (err.cause instanceof Error) out.cause = toPlain(err.cause);
return out;
}
const serialised = JSON.stringify(toPlain(failure));
const revived = JSON.parse(serialised);
const afterTheRoundTrip = [revived instanceof Error, revived.cause.message];
console.log('naive :', naive);
console.log('in a report :', insideAReport);
console.log('projected :', serialised);
console.log('String() :', String(failure));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('an Error stringifies to nothing but the fields you added yourself', naive, '{"till":"yaba","retryable":true}');
test('so a report that embeds one loses the actual reason', insideAReport, '{"status":"failed","error":{"till":"yaba","retryable":true}}');
test('because message is not enumerable and your own fields are', enumerability, [false, true]);
test('spreading loses exactly the same things, just as quietly', spreadKeys, ['till', 'retryable']);
test('a deliberate projection is what crosses the wire', serialised, '{"name":"Error","message":"yaba till timed out","cause":{"name":"Error","message":"ECONNRESET"}}');
test('and what comes back is a plain object, not an Error', afterTheRoundTrip, [false, 'ECONNRESET']);
test('String reads the prototype instead, so it works', String(failure), 'Error: yaba till timed out');
test('which is why an error logged as an object alone tells you nothing', JSON.stringify({ oops: { ...new Error('lost entirely') } }), '{"oops":{}}');
{} in a log line is this, every time. message and stack live on the error as non-enumerable properties, name is inherited from the prototype, and cause is non-enumerable too — so JSON.stringify, object spread and Object.assign all walk away with the enumerable fields you happened to attach and nothing that identifies the failure.
Note the asymmetry in the first assertion: till and retryable made it through precisely because you assigned them. That is what makes the bug so confusing in practice — the log entry is not empty, it just contains everything except the part you needed.
So serialise deliberately. toPlain is eight lines and it is the whole fix: name, message, the cause chain, and stack too if the destination is private. Add errors to it when the input might be an AggregateError, as in exercise 36. Some codebases put this on Error.prototype.toJSON, which makes JSON.stringify work everywhere at the cost of patching a builtin — defensible in an application, rude in a library.
The last two assertions are the practical rule of thumb. String(err) and template interpolation read the prototype and work; handing the object to a JSON logger does not. And what survives a round trip is a plain object: instanceof Error is false on the other side, so anything downstream that branches on the class needs reviving explicitly.