JavaScriptFundamental (ES6), part 2
Rethrow errors without losing the stack in JavaScript
37 Rethrowing without throwing the evidence away
hardPass one failure up three ways: rethrow it, rebuild it from its message, and wrap it with cause. Show what each keeps and what each destroys. Then write the handler that deals with the error it recognises and rethrows everything else untouched.
Stuck? Three hints, smallest first
- 1.
throw errhands the very same object up. Identity and stack are unchanged. - 2.
new Error(err.message)is a new object: new stack, no class, no cause. - 3. A handler that catches everything and reports it as its own problem is how a bug becomes unfindable.
class RepositoryError extends Error {
constructor(message, options) {
super(message, options);
this.name = 'RepositoryError';
}
}
const failures = [];
const driver = () => {
const err = new RepositoryError('duplicate key on tills.name');
failures.push(err); // so the test can compare identity
throw err;
};
const rethrown = () => { try { driver(); } catch (err) { throw err; } };
const rebuilt = () => { try { driver(); } catch (err) { throw new Error(err.message); } };
const wrapped = () => { try { driver(); } catch (err) { throw new Error('could not save the till', { cause: err }); } };
const bare = (() => {
try { rethrown(); } catch (err) { return { sameObject: err === failures.at(-1), name: err.name }; }
})();
const flat = (() => {
try { rebuilt(); } catch (err) {
return {
isRepositoryError: err instanceof RepositoryError,
causeMissing: err.cause === undefined,
sameStack: err.stack === failures.at(-1).stack,
};
}
})();
const kept = (() => {
try { wrapped(); } catch (err) {
return {
message: err.message,
causeIsOriginal: err.cause === failures.at(-1),
causeStillTyped: err.cause instanceof RepositoryError,
};
}
})();
// Handle what you understand; rethrow the rest exactly as it came.
const handleOnly = (fn) => {
try { return fn(); }
catch (err) {
if (err instanceof RepositoryError) return 'handled: ' + err.message;
throw err;
}
};
const mine = handleOnly(driver);
const notMine = (() => {
try { handleOnly(() => { throw new TypeError('cannot read property of undefined'); }); }
catch (err) { return err.name; }
})();
const target = new RepositoryError('carried across an await');
const acrossAwait = await (async () => {
try { await Promise.reject(target); } catch (err) { throw err; }
})().then(() => false, (err) => err === target);
console.log('rethrown :', bare);
console.log('rebuilt :', flat);
console.log('wrapped :', kept);
console.log('selective:', mine, '/ passed through:', notMine);
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('throw err passes the very same object up', [bare.sameObject, bare.name], [true, 'RepositoryError']);
test('rebuilding from the message loses the class', flat.isRepositoryError, false);
test('and loses the original, which is now unreachable', flat.causeMissing, true);
test('and carries a different stack: the rethrow site, not the failure site', flat.sameStack, false);
test('wrapping with cause keeps the original reachable and still typed', [kept.causeIsOriginal, kept.causeStillTyped], [true, true]);
test('while adding the context only this layer knew', kept.message, 'could not save the till');
test('a handler that knows one error rethrows the rest untouched', [mine, notMine], ['handled: duplicate key on tills.name', 'TypeError']);
test('identity survives a rejection and a catch across an await', acrossAwait, true);
Three ways up, and only two of them are honest. throw err is free and lossless: same object, same stack, same class, so the top of the application sees the failure exactly as it happened. Wrapping with cause costs one line and adds the context the lower layer could not know — which order, which customer — while keeping the original one hop away. new Error(err.message) keeps the sentence and destroys everything that made it debuggable.
The fourth assertion is the specific loss people underestimate. A stack is captured when the error is constructed, so a rebuilt error's stack points at your catch block, not at the line that actually failed. You end up with a trace whose deepest frame is your own error handling. Rethrowing the same object, or wrapping it, keeps the real trace intact underneath.
The selective handler is the shape to copy. catch (err) { log(err); return null; } around a whole operation is how a TypeError from a genuine bug gets reported as "could not save the till" and stays in the codebase for a year. Catch narrowly — by class, in one place — and let anything you did not anticipate keep travelling.