A buyer mistypes a voucher: SAVE01, when they meant SAVE10. What should the cashier do? A good cashier answers, "That code doesn't exist, did you mean SAVE10?" A bad cashier says nothing and charges full price. The buyer goes home thinking they got the discount, and nobody knows anything went wrong.
Error handling is deciding what happens when something goes wrong. It has one goal: the problem is heard, it's clear, and it reaches someone who can fix it.
Two things that can go wrong at the checkout
The checkout at Raka's T-Shirt Shop from the Small, Focused Functions lesson never complains. applyVoucher ignores every code other than SAVE10, and calculateTotal takes any cart:
> calculateTotal(cartA, 'SAVE01')
'Total: $245.00'
> calculateTotal([], '')
'Total: $15.00'
A mistyped voucher is ignored silently, so the buyer thinks the discount went in. An empty cart is charged $15: a subtotal of 0 is below $200, so it pays shipping for zero items. Neither is an error, both are wrong. There are three ways to report them.
return null: the problem moves
The first way: return null, "no result".
function applyVoucher(amount, voucherCode) {
if (voucherCode === '') return amount;
if (voucherCode === 'SAVE10') return amount - amount * VOUCHER_DISCOUNT;
return null; // unknown voucher
}
If calculateTotal forgets to check for null, what does cart A ($245) with SAVE01 give? An error, Total: $245.00, or something else? Guess first.
calculateTotal doesn't check for null and passes it on to addShipping. null < 200 is true, and null + 15 is 15, because JavaScript counts null as 0:
> calculateTotal(cartA, 'SAVE01')
'Total: $15.00'
Not an error, but a bill of $15 for $245 of shopping. null only moves the problem to the caller, and a caller that forgets to check gets no warning at all.
throw: stop, loudly
The second way: throw an error. The caller can't pretend not to see it; if nobody catches it, the program stops and the console points at the problem.
class VoucherError extends Error {
constructor(code) {
super('Voucher ' + code + ' is unknown');
this.name = 'VoucherError';
}
}
function applyVoucher(amount, voucherCode) {
if (voucherCode === '') return amount;
if (voucherCode === 'SAVE10') return amount - amount * VOUCHER_DISCOUNT;
throw new VoucherError(voucherCode);
}
function calculateTotal(cart, voucherCode) {
if (cart.length === 0) throw new Error('Cart is empty');
let total = calculateSubtotal(cart);
total = applyVoucher(total, voucherCode);
total = addShipping(total);
return 'Total: ' + formatPrice(total);
}
function checkout(cart, voucherCode) {
try {
return calculateTotal(cart, voucherCode);
} catch (e) {
if (e instanceof VoucherError) return e.message + '. Check the code again.';
throw e; // any other error, bugs included, keeps going up
}
}
class VoucherError extends Erroris a custom error: an error you make, with its own name.super(...)fills inmessage, andthis.namemakes the console printVoucherError: .... Alwaysthrow new ..., neverthrow 'text': anErrorobject carries a stack trace, the list of lines where the error happened.- The empty-cart check sits on the first line. A check at the top of a function like this is called a guard clause: fail as early as possible, before any calculation runs.
e instanceof VoucherErrorcatches only the error it knows how to handle. Everything else is thrown again withthrow e.
> checkout(cartA, 'SAVE01')
'Voucher SAVE01 is unknown. Check the code again.'
> checkout([], '')
Uncaught Error: Cart is empty
The empty cart is left to go up on purpose: the pay button shouldn't be pressable with an empty cart, so if one gets this far, that's a bug in the page and it has to show.
Result object: failure as an ordinary value
The third way: return an object that always says whether it worked, for example { ok: true, value: 220.5 } or { ok: false, error: 'Voucher SAVE01 is unknown' }. The caller has to read ok before it can use value, so forgetting to check is hard to do without noticing.
| Way | Fits | The danger |
|---|---|---|
throw |
what shouldn't happen: an empty cart reaching the checkout, a broken config file | caught too broadly, it swallows bugs too |
| result object | common, expected failure: a buyer mistyping a voucher | longer to write |
return null |
a normal "not found", such as searching for a product, checked right away | a caller that forgets to check passes null on silently |
Never swallow an error
Swallowing an error means catching it and carrying on as if nothing happened. An example that looks "safe":
function checkout(cart, voucherCode) {
try {
return calculateTotal(cart, voucherCode);
} catch (e) {
return calculateTotal(cart, ''); // "so it doesn't error": retry without the voucher
}
}
Then someone makes a typo in applyVoucher: VOUCHER_DISCONT. Every SAVE10 now throws a ReferenceError, the catch swallows it, and the checkout retries without the voucher:
> checkout(cartA, 'SAVE10')
'Total: $245.00'
It should be $220.50. Every SAVE10 buyer pays full price, with no error anywhere. With the instanceof version of checkout above, the same typo shows up on the first test: Uncaught ReferenceError: VOUCHER_DISCONT is not defined.
A catch that only logs and carries on is just as dangerous:
function getTotal(cart, voucherCode) {
try {
return calculateTotal(cart, voucherCode);
} catch (e) {
console.error(e.message); // logged, then... carry on
}
}
const total = getTotal(cartA, 'SAVE01');
console.log(total.replace('Total: ', ''));
Voucher SAVE01 is unknown
Uncaught TypeError: Cannot read properties of undefined (reading 'replace')
A function that never reaches return returns undefined, and the error blows up on another line that has nothing to do with it. An async function whose await fails behaves exactly the same. A good catch: catch a specific kind, log the details for the developer (console.error(e)), show the buyer a friendly message, and never show a stack trace to users.
Exercise: divide
In the exercise, divide returns null when dividing by zero. Make a class DivisionByZeroError extends Error with the message Cannot divide by zero and this.name = 'DivisionByZeroError'. divide(a, b) throws throw new DivisionByZeroError() when b === 0, otherwise return a / b. safeDivide(a, b) calls divide inside a try/catch: when the error is instanceof DivisionByZeroError, it returns the text 'Error: ' + e.message, and any other error is thrown again. The output:
5
Error: Cannot divide by zero
5
⚠️ Errors that vanish without a sound
return nullthat nobody checks.nulltakes part in arithmetic as 0:null + 15becomes15, with no error.- A catch that catches everything. It swallows bugs too, like the
VOUCHER_DISCONTtypo that makes every SAVE10 pay full price. Catch withinstanceof, throw the rest again. - A catch that only logs. The function returns
undefined, and the error turns into aTypeErrorsomewhere else. throw 'text'. Text carries no stack trace. Alwaysthrow new Error(...)or a subclass.- In the exercise, printing inside
safeDivide. IfsafeDivideprints and returns nothing, the second line becomesundefined. Return the text.
TL;DR: Good error handling makes a problem heard and gets it to someone who can fix it. A checkout that stays quiet loses mistyped vouchers and charges an empty cart $15. A return null nobody checks leaks: null + 15 gives Total: $15.00. throw with a custom error (class VoucherError extends Error, this.name) and a guard clause at the top of the function stops the problem where it happens; the caller catches only instanceof VoucherError and throws the rest again. A result object ({ ok, value, error }) fits expected failures. Never swallow an error: a catch-all that retries without the voucher hides a typo that makes every SAVE10 pay $245, and a catch that only calls console.error causes a TypeError elsewhere. Catch what's specific, log the details, show users a friendly message. In the exercise: DivisionByZeroError, throw new, and safeDivide returning Error: Cannot divide by zero.
⚡ return null: the problem moves
Write:
function applyVoucher(amount, voucherCode) {
if (voucherCode === '') return amount;
if (voucherCode === 'SAVE10') return amount - amount * VOUCHER_DISCOUNT;
return null; // unknown voucher
}
Guess first: calculateTotal forgets to check for null. What does cart A ($245) with SAVE01 give?
Total: $15.00. null < 200 is true, and null + 15 is 15, because JavaScript counts null as 0. No error at all.
Meaning: return null only moves the problem to the caller. A caller that forgets to check gets no warning.
⚡ throw: stop, loudly
Write:
class VoucherError extends Error {
constructor(code) {
super('Voucher ' + code + ' is unknown');
this.name = 'VoucherError';
}
}
Meaning: This is a custom error, an error you make with its own name. Always throw new ..., never throw 'text', because an Error object carries a stack trace. The empty-cart check on a function's first line is called a guard clause: fail as early as possible.
⚡ Never swallow an error
Write:
} catch (e) {
return calculateTotal(cart, ''); // "so it doesn't error": retry without the voucher
}
Guess first: then someone makes a typo in applyVoucher, VOUCHER_DISCONT. What does checkout(cartA, 'SAVE10') give?
'Total: $245.00', when it should be $220.50. The ReferenceError is swallowed, every SAVE10 buyer pays full price, and there's no error anywhere.
Meaning: Catch what's specific with e instanceof VoucherError and throw the rest again with throw e. Log the details for the developer, and show the buyer a friendly message.