Skip to Content
JavaScriptAdvanceError Handling & Debugging

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(); }
  • catch receives the thrown error.
  • finally runs 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.group for quick inspection.
  • Browser DevTools breakpoints, watches, and call stack inspection.
  • Node.js --inspect mode to debug server scripts.

5) Promise Rejection Handling ⚠️

  • Always .catch or use top-level window.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 .catch or 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