Throw and catch errors in TypeScript
1 Throw when a condition is not met, then catch it
easyWrite a function that throws when some condition fails. Wrap a call to it in try/catch and report the message.
Stuck? Three hints, smallest first
- 1. Throw an
Errorobject, never a bare string. Only objects carry a stack trace. - 2. In TypeScript the caught value is typed
unknown, so you must narrow it before reading.message. - 3.
err instanceof Erroris the narrowing you want.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
function withdraw(balance: number, amount: number): number {
if (amount > balance) {
throw new Error(`cannot withdraw ${amount}; balance is ${balance}`);
}
return balance - amount;
}
// The catch parameter is 'unknown', so it has to be narrowed before use.
function attempt(fn: () => number): string {
try {
return `ok: ${fn()}`;
} catch (err) {
if (err instanceof Error) return `refused: ${err.message}`;
return 'refused: something that was not an Error';
}
}
console.log(attempt(() => withdraw(1000, 400)));
console.log(attempt(() => withdraw(1000, 5000)));
// Why 'throw new Error' and not 'throw "text"': only the object has a stack.
let hasStack = false;
try {
withdraw(10, 99);
} catch (err) {
hasStack = err instanceof Error && typeof err.stack === 'string';
}
test('a permitted withdrawal', withdraw(1000, 400), 600);
test('the good path reports ok', attempt(() => withdraw(1000, 400)), 'ok: 600');
test('the bad path is caught', attempt(() => withdraw(1000, 5000)), 'refused: cannot withdraw 5000; balance is 1000');
test('the thrown value carried a stack', hasStack, true);
Output
The detail people trip on is that catch (err) gives you unknown, not Error. That is correct, because JavaScript lets you throw anything at all. The instanceof Error check is what turns it into something you can read .message from.