javascript · level 3 · unit 3 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
classes tell different problems apart.
One plain Error for everything forces you to read messages to work out what went wrong. Instead, make a custom error: a class that extends Error, sets its own name, and can carry extra data such as the field that failed.
Then catch can sort problems with instanceof. Handle the ones you expect, like bad user input. Anything else, such as a typo in your own code, you with throw error, so a real bug is never quietly swallowed.
class ValidationError extends Error {
constructor(field, message) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function checkEmail(email) {
if (!email.includes("@")) { throw new ValidationError("email", "needs an @"); }
}
try {
checkEmail("sam.example.com");
} catch (error) { console.log(error instanceof ValidationError, `${error.field} ${error.message}`); } With no extra data, the short form works too: class NotFoundError extends Error { name = "NotFoundError"; }.
guess first
Nobody catches it. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class OutOfStockError extends Error {
constructor(item) {
super(`${item} is sold out`);
this.name = "OutOfStockError";
}
}
function buy(item, stock) {
if (stock === 0) { throw new OutOfStockError(item); }
return `Bought ${item}`;
}
console.log(buy("socks", 3));
console.log(buy("hats", 0));
your turn
Your turn. Handle a missing order, rethrow the rest.
In the first blank, type an order id that does not exist. In the second, name the error class this catch knows how to handle.
fix it
The helpful message vanished. Can you fix it?
- The message shows as
undefined. Which class normally stores the message you pass tonew? ValidationErroris not built onError, so nothing keeps the message you gave it.- Change line 1 to
class ValidationError extends Error { name = "ValidationError"; }, then press run.
nailed it
your errors have names now. :D
- Extend
Errorto make a class for each kind of problem. - Use
instanceofincatchto handle the ones you expect. - Rethrow anything else, so real bugs stay visible.
new words in your collection
- custom error
- rethrow
This lesson isn’t saved. A free account remembers every lesson you finish.