0Pricing
JavaScript Academy · Lesson

Error boundaries (conceptual) without frameworks

Create tiny error boundaries in plain JS: try/catch around risky code, wrapper helpers, async try/catch, fallback values, and minimal logging.

Big picture

Goal: Stop one failure from breaking the whole screen.

  • Use try/catch around risky spots
  • Add a tiny runSafe helper
  • Handle async with try/catch too
  • Return fallbacks and log briefly
Error boundaries (conceptual) without frameworks — illustration 1

Local boundary: parsing

Wrap only the risky step (JSON.parse). Return a simple fallback object on failure.

// Try/catch boundary: parse user JSON with a fallback
function safeParseUser(json) {
  try {
    const obj = JSON.parse(json);
    // minimal validation
    if (!obj || typeof obj.name !== "string") {
      return { name: "Guest" };
    }
    return { name: obj.name };
  } catch (err) {
    // fallback on parse error
    return { name: "Guest" };
  }
}

console.log("ok:", safeParseUser("{\"name\":\"Ayla\"}"));
console.log("bad:", safeParseUser("{oops}"));
Error boundaries (conceptual) without frameworks — illustration 2

All lessons in this course

  1. Input validation, escaping basics
  2. Safe object merging; freezing & sealing
  3. Error boundaries (conceptual) without frameworks
← Back to JavaScript Academy