JavaScriptFundamental (ES6), part 2
Find the root cause in an error chain in JavaScript
35 Walking a cause chain to the root
fairWrap a low-level failure twice, then write chainOf(err) and rootCause(err) that walk cause to the bottom. Make the walk survive a cycle, and check what cause does to serialisation.
Stuck? Three hints, smallest first
- 1. Each layer adds the context it has: the socket knows the reset, the service knows the order number.
- 2. Walk with
while (current instanceof Error)— the chain ends whencauseis missing or is not an error. - 3. Keep a
Setof errors already visited, or a chain that loops back will spin for ever.
const socket = new Error('ECONNRESET from the card network');
const driver = new Error('charge request failed', { cause: socket });
const service = new Error('could not take payment for order LAG-0035', { cause: driver });
function chainOf(err) {
const messages = [];
const seen = new Set();
let current = err;
while (current instanceof Error && !seen.has(current)) {
seen.add(current);
messages.push(current.message);
current = current.cause;
}
return messages;
}
function rootCause(err) {
const seen = new Set();
let current = err;
while (current.cause instanceof Error && !seen.has(current.cause)) {
seen.add(current);
current = current.cause;
}
return current;
}
const loopA = new Error('a');
const loopB = new Error('b', { cause: loopA });
loopA.cause = loopB; // a cycle, by accident
const report = chainOf(service).map((m, depth) => ' '.repeat(depth) + m).join('\n');
console.log('the chain, outside in:');
console.log(report);
console.log('root cause :', rootCause(service).message);
console.log('serialised :', JSON.stringify(service), Object.keys(service));
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('the chain reads outside in', chainOf(service), ['could not take payment for order LAG-0035', 'charge request failed', 'ECONNRESET from the card network']);
test('and the root cause is the one worth alerting on', rootCause(service).message, 'ECONNRESET from the card network');
test('a plain error is a chain of one, and its own root', [chainOf(socket).length, rootCause(socket) === socket], [1, true]);
test('cause exists only when you pass it', ['cause' in service, 'cause' in socket], [true, false]);
test('but passing cause: undefined installs the property anyway', 'cause' in new Error('x', { cause: undefined }), true);
test('cause is not enumerable, so the chain does not serialise', [Object.keys(service), JSON.stringify(service)], [[], '{}']);
test('the walk terminates on a cycle instead of hanging', chainOf(loopB), ['b', 'a']);
test('a non-error cause ends the walk rather than breaking it', chainOf(new Error('top', { cause: 'just a string' })), ['top']);
Every layer knows something the others do not. The socket knows the reset; the driver knows which request; the service knows which order and which customer is waiting. cause is what lets each one add its context without deleting what came before, and rootCause is what an alert should fire on — the outermost message is the most human but the least diagnostic.
The cycle guard is not paranoia. Two errors that reference each other is an easy accident in retry code that attaches the previous failure as the cause of the next, and without the Set the walk is an infinite loop in your error handler, which is the worst possible place for one. The same guard is why chainOf checks instanceof Error rather than truthiness: cause can hold anything, including a string or a response object, and the walk should stop rather than throw.
The serialisation assertion is the practical sting. cause is defined non-enumerably by the spec, so a chain three deep is invisible to JSON.stringify, to a spread and to most log shippers. Node's console.error and util.inspect print it because they were taught to; your logger has to be taught too, which is what exercise 42 builds.