Error Handling 🛡️
Plan for failures so your app can recover gracefully.
1) try/catch/finally 🔁
try {
const data = JSON.parse(payload);
process(data);
} catch (error) {
console.error("Parsing failed", error);
} finally {
cleanup();
}catchreceives the thrown error.finallyruns regardless of success/failure.
2) Throwing Errors 🚨
function assert(condition, message) {
if (!condition) {
throw new Error(message);
}
}- Throw built-in errors (
Error,TypeError,RangeError) or custom subclasses.
3) Custom Errors 🎯
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}- Add context (name, metadata) for smarter error handling.
4) Debugging Techniques 🧰
console.log,console.table,console.groupfor quick inspection.- Browser DevTools breakpoints, watches, and call stack inspection.
- Node.js
--inspectmode to debug server scripts.
5) Promise Rejection Handling ⚠️
- Always
.catchor use top-levelwindow.addEventListener("unhandledrejection", ...)to log unexpected rejections. - With async/await, wrap calls in
try...catch.
Key Takeaways ✅
- Use try/catch for synchronous code; async code needs
.catchor try/await. - Throw meaningful errors to guide callers.
- Lean on DevTools to pause, inspect, and understand control flow.
Recap 🔄
Robust JavaScript apps expect errors: validate inputs, throw helpful messages, catch failures early, and use debugging tools to trace issues faster.
Last updated on