Error handling: fail loudly, recover deliberately
throw, try, catch, finally, custom errors and the difference between a bug and an expected failure.
Lesson 16 of 23 in JavaScript11 min1 exercise
When something cannot continue, throw an Error. The current function stops and the error travels up the call stack until something catches it — or the program crashes.
function divide(a, b) {
if (b === 0) throw new Error("Cannot divide by zero");
return a / b;
}
try {
divide(1, 0);
} catch (error) {
console.log(error.message); // "Cannot divide by zero"
} finally {
console.log("always runs");
}finally runs whether or not there was an error — good for cleanup. Catch only what you can handle. A bare catch {} that swallows everything hides bugs instead of fixing them.
Custom error types
class ValidationError extends Error {
constructor(field) {
super(`Invalid field: ${field}`);
this.name = "ValidationError";
this.field = field;
}
}
try {
throw new ValidationError("email");
} catch (error) {
if (error instanceof ValidationError) {
console.log("fix the " + error.field + " field");
} else {
throw error; // not mine, let it bubble
}
}Try it
Catch, inspect, recover
main.js
console · output appears here
Exercises
Checked in your browser · hints and solutions included
01
Exercise
A parse that never crashes
Write safeParse(text) that returns:
{ ok: true, value }whentextis valid JSON{ ok: false, error }when it is not, whereerroris the message string from the thrown error
safeParse("nope") must not throw.
exercise.js
console · run your code or check the answer