IntermediateLesson 10 of 16
Error Handling – JavaScript
try/catch/finally, custom error classes and typical error types.
Errors (exceptions) terminate the program if you do not catch them with try/catch. Every error object has name, message and stack.
try {
JSON.parse("{broken");
} catch (e) {
console.log("Invalid:", e.name); // SyntaxError
} finally {
console.log("Always runs");
}
try {
null.eigenschaft;
} catch (e) {
console.log(e.name); // TypeError
}
try {
nichtDefiniert + 1;
} catch (e) {
console.log(e.name); // ReferenceError
}With throw you raise errors yourself. Always throw Error objects (not strings), ideally with a custom class – then you can react specifically with instanceof:
class KontoFehler extends Error {
constructor(message) {
super(message);
this.name = "KontoFehler";
}
}
function abheben(saldo, betrag) {
if (betrag > saldo) throw new KontoFehler("Insufficient balance");
return saldo - betrag;
}
try {
abheben(50, 100);
} catch (e) {
if (e instanceof KontoFehler) console.log("Error:", e.message);
else throw e; // pass on anything unknown
}Since ES2022 you can attach the cause (cause), and the catch parameter is optional:
function laden(text) {
try {
return JSON.parse(text);
} catch (ursache) {
throw new Error("Invalid configuration", { cause: ursache });
}
}
try {
laden("{");
} catch (e) {
console.log(e.message, "->", e.cause.name);
}
try { JSON.parse("x"); } catch { console.log("Cause doesn't matter"); }Warning
fetch does not throw on HTTP errors like 404 or 500, only on network problems. Check response.ok yourself. And never catch errors just to swallow them – log them or pass them on.