Error Handling

Published by Brayan K

Errors are not signs of failure — they are signals. Learn everything from basic try/catch to advanced real-world error architectures used in production apps.

Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Follow the execution path before choosing a recovery

An exception changes which statements run. The nearest active matching catch receives the thrown value; execution does not resume at the failed statement. A catch that returns a replacement value has made a recovery decision. If that replacement is misleading, the program can appear to succeed while losing the original problem.

function attempt(fail) {
  console.log("start");
  try {
    console.log("work");
    if (fail) throw new Error("Unavailable"); // The remaining try statements are skipped on this path.
    console.log("complete");
  } catch (error) {
    console.log("caught", error.message);
  } finally {
    console.log("cleanup"); // Runs before this entered try finishes, on either path.
  }
  console.log("after");
}
attempt(false);
console.log("---");
attempt(true);

// ✅ Expected output:
// start
// work
// complete
// cleanup
// after
// ---
// start
// work
// caught Unavailable
// cleanup
// after

On the failing path, complete is skipped. The catch handles the exception, finally runs, and after is reached. Removing the catch would let the error continue outward after cleanup. Functions owns function returns and calls; this lesson owns the decision to recover, rethrow or add context.

function readQuantity(value) {
  if (!Number.isInteger(value) || value < 0) {
    throw new RangeError("Quantity must be a non-negative integer");
  }
  return value;
}
console.log("before");
readQuantity(-1);
console.log("after");

// ✅ Expected output:
// before

// ✅ Expected error:
// RangeError: Quantity must be a non-negative integer

This error is the function’s explicit contract. JavaScript itself does not reject every unwanted result: dividing by zero produces Infinity, and a misspelled calculation may produce the wrong number without throwing. Error handling does not replace checking results.

console.log(10 / 0);
console.log(Number.isFinite(10 / 0));
console.log("continues");

// ✅ Expected output:
// Infinity
// false
// continues

Create useful errors and keep the protected operation small

Throw an Error object, usually a built-in subclass or an application-specific subclass. Error.message explains the failure; Error.name identifies a category. A TypeError can also reveal a programming mistake, so catching every TypeError and calling it invalid user input can conceal a bug.

const user = null;
console.log(user.name);

// ✅ Expected error:
// TypeError: Cannot read properties of null (reading 'name')

The displayed diagnostic is the output from the checked Node and Chromium engines. Other engines can word built-in messages differently. Do not branch on a full human-readable message. Error stacks also vary by engine, source file and runtime; the lesson prints stable fields rather than invented stack traces.

try {
  throw "Unavailable";
} catch (error) {
  console.log(typeof error);
  console.log(error.message);
}
try {
  throw new Error("Unavailable");
} catch (error) {
  console.log(error.name);
  console.log(error.message);
}

// ✅ Expected output:
// string
// undefined
// Error
// Unavailable

The first throw is legal but loses the consistent Error interface. If you are calling code that can throw arbitrary values, do not assume every caught value has a message or a cause. The examples below control their own thrown types.

function parseOrExplain(text) {
  try {
    return { ok: true, value: JSON.parse(text) };
  } catch (error) {
    if (!(error instanceof SyntaxError)) throw error;
    return { ok: false, reason: "Invalid JSON" };
  }
}
console.log(JSON.stringify(parseOrExplain('{"quantity":0}')));
console.log(JSON.stringify(parseOrExplain("{")));
console.log(JSON.stringify(parseOrExplain("null")));

// ✅ Expected output:
// {"ok":true,"value":{"quantity":0}}
// {"ok":false,"reason":"Invalid JSON"}
// {"ok":true,"value":null}

Only JSON parsing sits inside this catch. A valid JSON null is still a successful parse; a separate schema check decides whether it fits the application. Deep Dive into JSON, Parsing & Serialization owns JSON representation and validation details.

Handle an expected failure; rethrow an unexpected one

Use a distinct error type when callers need to distinguish a documented input problem from unrelated failures. The class below adds a name and inherits Error; Prototypes and Classes owns inheritance syntax and prototype relationships.

class QuantityError extends Error {
  constructor(message) {
    super(message);
    this.name = "QuantityError";
  }
}
function parseQuantity(value) {
  if (!Number.isInteger(value) || value < 0 || value > 20) {
    throw new QuantityError("Choose a whole quantity from 0 to 20");
  }
  return value;
}
function saveOrder(value, save) {
  let quantity;
  try {
    quantity = parseQuantity(value);
  } catch (error) {
    if (!(error instanceof QuantityError)) throw error;
    return { ok: false, reason: error.message };
  }
  save(quantity);
  return { ok: true, quantity };
}
console.log(JSON.stringify(saveOrder(-1, () => {})));
console.log(JSON.stringify(saveOrder(0, () => {})));
try {
  saveOrder(2, () => { throw new Error("Storage unavailable"); });
} catch (error) {
  console.log(error.message);
}

// ✅ Expected output:
// {"ok":false,"reason":"Choose a whole quantity from 0 to 20"}
// {"ok":true,"quantity":0}
// Storage unavailable

Storage failure is outside the input-recovery catch and reaches the caller. It does not become a successful order with quantity zero. The small catch also avoids categorizing errors from save as validation failures.

const original = new Error("Storage unavailable");
try {
  try {
    throw original;
  } catch (error) {
    throw error;
  }
} catch (error) {
  console.log(error === original);
  console.log(error.message);
}

// ✅ Expected output:
// true
// Storage unavailable

If a boundary can add useful context, construct a new Error with the original value as cause. That preserves the relationship rather than replacing the failure with an unrelated message. Do not assume cause is always an Error: the language permits any value.

const original = new Error("Storage unavailable");
function saveProfile() {
  try {
    throw original;
  } catch (error) {
    throw new Error("Could not save profile", { cause: error });
  }
}
try {
  saveProfile();
} catch (error) {
  console.log(error.message);
  console.log(error.cause === original);
  console.log(error.cause.message);
}

// ✅ Expected output:
// Could not save profile
// true
// Storage unavailable

An error message for the person using your app and diagnostic information for a developer serve different purposes. Avoid displaying raw tokens, private response bodies or stack details to users. Error Handling Patterns in Large JS Apps owns broader reporting and application-wide recovery policies.

Use finally for cleanup, and keep it from replacing the result

For an entered try statement, normal completion, a return and an exception all pass through finally before control leaves the statement. This is a language control-flow rule, not a guarantee that cleanup survives a killed process, closed tab or an operation that never finishes.

let busy = false;
function perform(action) {
  busy = true;
  try {
    return action();
  } finally {
    busy = false;
    console.log("busy", busy);
  }
}
console.log(perform(() => "saved"));
try {
  perform(() => { throw new Error("Failed"); });
} catch (error) {
  console.log(error.message);
}
console.log("after", busy);

// ✅ Expected output:
// busy false
// saved
// busy false
// Failed
// after false

A return in finally replaces a return or throw that was already pending. This is usually a bug: the cleanup code silently changes the operation’s meaning.

function misleading() {
  try {
    throw new Error("Save failed");
  } finally {
    return "saved";
  }
}
console.log(misleading());

// ✅ Expected output:
// saved

A cleanup operation can fail too. If it throws while another exception is pending, its exception replaces the earlier one. Keep cleanup simple; when multiple failures matter, decide how to preserve and report both rather than quietly losing one.

try {
  try {
    throw new Error("Work failed");
  } finally {
    throw new Error("Cleanup failed");
  }
} catch (error) {
  console.log(error.message);
}

// ✅ Expected output:
// Cleanup failed

Catch the operation while it is actually active

A syntax error in the surrounding program prevents that program’s try statement from running at all. Here, new Function parses a separate, fixed source string at runtime. Its inner catch cannot run because that string is invalid; the outer program can catch the constructor’s SyntaxError. Do not use dynamic compilation to process untrusted input.

try {
  new Function('try { const value = ; } catch (error) { console.log("inner"); }');
} catch (error) {
  console.log(error.name);
}

// ✅ Expected output:
// SyntaxError

For a promise rejection, the rejecting operation must be awaited inside the try, or handled through its promise chain. Merely obtaining a promise does not make a later rejection a synchronous throw. Async/Await owns that timing and return-await distinction.

async function save() {
  throw new Error("Save failed");
}
try {
  await save();
} catch (error) {
  console.log(error.message);
}
console.log("handled");

// ✅ Expected output:
// Save failed
// handled

Likewise, a callback invoked after a surrounding try has finished needs handling at its own execution boundary. Callbacks & Callback Hell demonstrates that boundary with deterministic microtasks. A global error listener is for observation or last-resort reporting, not a way to resume the failed statement.

Guided exercise: reject invalid input and preserve other failures

Fill each blank using its literal hint. The caller should recover from the documented RangeError and let other error types propagate. Zero is a valid quantity.

function quantity(value) {
  if (!Number.isInteger(value) || value < 0) {
    ___ new RangeError("Invalid quantity"); // 👉 replace ___ with throw
  }
  return value;
}
function show(value) {
  try {
    return String(quantity(value));
  } catch (error) {
    if (error instanceof ___) return "Choose a whole quantity"; // 👉 replace ___ with RangeError
    throw ___; // 👉 replace ___ with error
  }
}
console.log(show(0));
console.log(show(-1));

// ✅ Expected output:
// 0
// Choose a whole quantity

Independent brief: report malformed input without hiding a broken save

Write submitOrder(text, save). The text must parse as a non-null, non-array object whose quantity is an integer from 0 through 20. Invalid JSON returns an object with ok: false and reason: "Invalid JSON"; invalid shape or quantity returns an object with ok: false and reason: "Invalid quantity". Valid input calls save(quantity) once and returns an object with ok: true and the accepted quantity. A save failure must propagate unchanged. Extra input fields are ignored.

Check zero, the upper bound, a negative value, a fraction, a numeric string, null, an array, malformed JSON and a throwing save. No network or persistent storage is involved: save is an injected callback.

function submitOrder(text, save) {
  let data;
  try {
    data = JSON.parse(text);
  } catch (error) {
    if (!(error instanceof SyntaxError)) throw error;
    return { ok: false, reason: "Invalid JSON" };
  }
  if (data === null || Array.isArray(data) || typeof data !== "object" ||
      !Number.isInteger(data.quantity) || data.quantity < 0 || data.quantity > 20) {
    return { ok: false, reason: "Invalid quantity" };
  }
  save(data.quantity);
  return { ok: true, quantity: data.quantity };
}
const saved = [];
for (const text of [
  '{"quantity":0}', '{"quantity":20}', '{"quantity":-1}',
  '{"quantity":1.5}', '{"quantity":"2"}', 'null', '[]', '{'
]) {
  console.log(JSON.stringify(submitOrder(text, quantity => saved.push(quantity))));
}
console.log("saved", saved.join(","));
const failure = new Error("Storage unavailable");
let attempts = 0;
try {
  submitOrder('{"quantity":2}', () => { attempts++; throw failure; });
} catch (error) {
  console.log(error === failure, error.message);
}
console.log("attempts", attempts);

// ✅ Expected output:
// {"ok":true,"quantity":0}
// {"ok":true,"quantity":20}
// {"ok":false,"reason":"Invalid quantity"}
// {"ok":false,"reason":"Invalid quantity"}
// {"ok":false,"reason":"Invalid quantity"}
// {"ok":false,"reason":"Invalid quantity"}
// {"ok":false,"reason":"Invalid quantity"}
// {"ok":false,"reason":"Invalid JSON"}
// saved 0,20
// true Storage unavailable
// attempts 1

The two expected input failures use explicit result objects. The unexpected save failure remains an exception, preserving its object identity. Neither empty catch blocks nor fabricated default quantities are needed. This contract does not include retries, transactions or durable storage; those need their own design.

Practice quiz

What does this complete program print? try { console.log("before"); throw new Error("Failed"); console.log("after"); } catch (error) { console.log(error.message); }

  • before Failed
  • before after Failed
  • Failed before
  • before after

Answer: before Failed. Execution jumps out of the try at throw; it does not resume at the skipped log.

What does this complete program print? try { throw "Failed"; } catch (error) { console.log(error.message); }

  • Failed
  • undefined
  • Error
  • null

Answer: undefined. A thrown string has no message property. Prefer an Error interface for your own failures.

What does this complete program print? function run() { try { return "result"; } finally { console.log("cleanup"); } } console.log(run());

  • result cleanup
  • cleanup
  • cleanup result
  • undefined

Answer: cleanup result. The return value is selected, then finally runs, then the function returns.

What does this complete program print? function run() { try { throw new Error("Failed"); } finally { return "fallback"; } } console.log(run());

  • Error: Failed
  • undefined
  • Failed fallback
  • fallback

Answer: fallback. Returning from finally replaces the pending throw, which is why it can hide failures.

What does this complete program print? const original = new Error("Cause"); const wrapped = new Error("Context", { cause: original }); console.log(wrapped.cause === original); console.log(wrapped.message);

  • true Context
  • false Context
  • true Cause
  • false Cause

Answer: true Context. The new message adds context while cause retains the original error object.

What does this complete program print? let handled = false; try { console.log(1 / 0); } catch { handled = true; } console.log(handled);

  • RangeError true
  • Infinity false
  • Infinity true
  • 0 false

Answer: Infinity false. Division by zero produces Infinity; it does not throw a JavaScript exception.

What does this complete program print? async function fail() { throw new Error("Unavailable"); } try { await fail(); } catch (error) { console.log(error.message); }

  • undefined
  • [object Promise]
  • Unavailable
  • No output

Answer: Unavailable. Awaiting the rejecting promise inside try makes its rejection available to this catch.

What does this complete program print? const failure = new Error("Same object"); try { try { throw failure; } catch (error) { throw error; } } catch (error) { console.log(error === failure); }

  • false
  • undefined
  • Same object
  • true

Answer: true. Rethrowing the caught value preserves its identity.

Continue this course

Related lessons