Error Handling Patterns in Large JavaScript Apps
Published by Brayan K
Error handling patterns are reusable strategies — such as try/catch, custom error classes, and centralized handlers — for catching, classifying, and recovering from failures so large JavaScript apps stay reliable.
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.
Put recovery at the layer that can make a meaningful decision
A low-level function knows what failed; a user-facing boundary knows what the user can do next. Catching an error at every layer often creates duplicate reports, invented success values or lost causes. We will define explicit outcomes and test one boundary that owns classification and reporting. Error Handling owns try/catch, finally and ordinary propagation; this lesson owns decisions across application layers.
class MissingRecord extends Error {}
async function repository(id) {
if (id !== "known") throw new MissingRecord("record not found");
return { id };
}
async function service(id) { return repository(id); } // No recovery decision belongs here.
async function screen(id) {
try { return { status: "ready", record: await service(id) }; }
catch (error) {
if (error instanceof MissingRecord) return { status: "missing" };
throw error; // Unexpected failures remain visible to the next owner.
}
}
console.log((await screen("known")).status);
console.log((await screen("absent")).status);
// ✅ Expected output:
// ready
// missingThe service adds no useful context or fallback, so it does not catch and log. The screen handles only the category it understands. This is an ownership choice, not a rule that every application needs three named layers.
An empty result and a failed request must remain distinguishable
async function load() { throw new Error("database unavailable"); }
async function hiddenFailure() {
try { return await load(); } catch { return []; }
}
const rows = await hiddenFailure();
console.log(rows.length, rows.length === 0 ? "no records" : "records");
// ✅ Expected output:
// 0 no recordsasync function capture(operation) {
try { return { status: "ok", value: await operation() }; }
catch (reason) { return { status: "failed", reason }; }
}
for (const operation of [() => [], () => 0, () => { throw undefined; }]) {
const result = await capture(operation);
console.log(result.status, result.status === "failed" ? Object.hasOwn(result, "reason") : Array.isArray(result.value));
}
// ✅ Expected output:
// ok true
// ok false
// failed trueA thrown value may be undefined, false, zero or a string. A tuple whose caller checks if(error) cannot safely represent every JavaScript rejection. With a tag, success containing undefined and failure throwing undefined remain different states. The wrapper only captures work it awaits; it cannot observe detached work that the operation neither returns nor handles.
for (const reason of [undefined, false, 0, ""]) {
try { await Promise.reject(reason); }
catch (error) { console.log("caught", error === reason, Boolean(error)); }
}
// ✅ Expected output:
// caught true false
// caught true false
// caught true false
// caught true falseClassify a stable category, not a sentence meant for people
class InputError extends Error {
constructor(field, message) { super(message); this.name = "InputError"; this.field = field; }
}
const first = new InputError("email", "Enter an address");
const second = new InputError("email", "Address required");
console.log(first.message === second.message, first instanceof InputError, second instanceof InputError);
console.log(first.field === second.field);
// ✅ Expected output:
// false true true
// trueMessages can change with wording, localization and dependencies. Within one application realm, an owned error class or validated discriminant gives a more stable policy boundary. An instanceof check does not recognize every cross-realm or serialized error. Validate remote response data into a known application category instead of blindly trusting a server-supplied object to dictate UI or retry policy.
const original = new Error("storage read failed");
function loadSettings() {
throw new Error("settings could not be loaded", { cause: original });
}
try { loadSettings(); }
catch (error) {
console.log(error.message, error.cause === original);
console.log(error === original);
}
// ✅ Expected output:
// settings could not be loaded true
// falseThe wrapper is a new error, while cause retains the original object. Add context where it helps the next owner; do not wrap mechanically at every function call. A UI should show a safe recovery message rather than dumping a cause chain, stack trace, authorization header or raw response payload.
Report once, and do not let a reporter erase the original outcome
const reports = [];
const reason = new Error("failure");
function repository() { throw reason; }
function service() {
try { return repository(); } catch (error) { reports.push("service"); throw error; }
}
try { service(); } catch (error) { reports.push("screen"); }
console.log(reports.join(","));
// ✅ Expected output:
// service,screenconst original = { code: "operation failed" };
const reports = [];
async function report(event) { reports.push(event.kind); throw new Error("reporter unavailable"); }
let reportingFailed = false;
try { throw original; }
catch (reason) {
try { await report({ kind: "unexpected" }); } catch { reportingFailed = true; }
console.log(reason === original, reportingFailed, reports.join(","));
}
// ✅ Expected output:
// true true unexpectedThe reporting failure is a separate operational fact; it must not replace the application failure or create a second unhandled rejection. This example awaits reporting, so a reporter that never settles would also keep this boundary pending. A real reporting queue needs its own bounded lifetime and overflow policy. The final brief explicitly awaits its injected reporter and records reportingFailed.
Cancellation is a caller-owned outcome, not a message substring
const controller = new AbortController();
const cancelled = { kind: "cancel" }, unrelated = new Error("bug");
controller.abort(cancelled);
for (const reason of [cancelled, unrelated]) {
console.log(controller.signal.aborted && reason === controller.signal.reason ? "cancelled" : "failed");
}
// ✅ Expected output:
// cancelled
// failedThis contract recognizes the exact supplied reason. Checking only signal.aborted would misclassify an unrelated error that happened at the same time. Libraries can wrap or transform abort errors, so adapt their documented behaviour at their boundary; there is no universal cancellation classifier based on one name or message. AbortController & Cancelling Async Work owns signals, and Advanced Fetch API Patterns (Retry, Timeout, AbortController) owns request retry/deadline policy.
Concurrent failure does not undo completed effects
const changes = [];
const first = async () => { changes.push("saved A"); return "A"; };
const second = async () => { throw new Error("B failed"); };
try { await Promise.all([first(), second()]); } catch (error) { console.log(error.message); }
console.log(changes.join(","));
// ✅ Expected output:
// B failed
// saved APromise.all observes results; it is not a transaction or rollback mechanism. Use a service’s real transactional facilities where atomicity is required. Compensating actions also need an explicit policy and can themselves fail. Async/Await Architecture & Best Practices owns concurrent outcome handling.
const cached = [{ id: "old" }];
async function load() { throw new Error("unavailable"); }
let result;
try { result = { status: "fresh", rows: await load() }; }
catch { result = { status: "stale", rows: cached }; }
console.log(result.status, result.rows[0].id);
// ✅ Expected output:
// stale oldStale data may be useful for a read-only view and unacceptable for an action requiring current facts. A fallback is a product decision. It does not repair the failed source or justify silently claiming a write succeeded.
Global handlers are last-resort observation points
Browser error and unhandledrejection events can help observe failures that escaped local ownership. They do not resume the failed operation or supply its missing return value. Registering a global handler is not a substitute for awaiting the promise you started. Reporting should redact sensitive data and avoid a loop in which the reporting path repeatedly reports itself.
React error boundaries cover their documented rendering/lifecycle failure scope; they do not automatically catch every event-handler or asynchronous callback failure. This plain JavaScript lesson does not emulate React. Consult the React error-boundary reference when integrating this policy into React.
Guided exercise: discriminate a falsy rejection
Fill the literal hints. Preserve the thrown reason and check the outcome tag, even though the reason itself is false.
async function capture(operation) {
try { return { status: "ok", value: await operation() }; }
catch (reason) { return { status: "failed", ___ }; } // 👉 replace ___ with reason
}
const result = await capture(() => { throw false; });
if (result.___ === "failed") { // 👉 replace ___ with status
console.log(result.reason === ___); // 👉 replace ___ with false
}
// ✅ Expected output:
// trueIndependent brief: one boundary with four explicit outcomes
Write runOperation(operation, options) with an injected report function and optional AbortSignal. Validate both functions before entering the recovery boundary. Await the operation, check cancellation before and after it, and return ok with the exact value on success. Return cancelled only for the exact reason of the supplied aborted signal. Return invalid for an owned InputError with its field/code.
For any other thrown or rejected value, call report exactly once with only the public event kind operation-failed. Await it, suppress its failure without replacing the original reason, and return failed with reason and reportingFailed. Do not retry, stringify the raw reason or copy private payloads into the report. Check false/undefined failures, synchronous throws, asynchronous rejections, invalid input, pre-cancellation, unrelated error during cancellation and a failing reporter.
class InputError extends Error {
constructor(field, code) {
super("invalid input"); this.name = "InputError";
this.field = field; this.code = code;
}
}
async function runOperation(operation, { report, signal } = {}) {
if (typeof operation !== "function" || typeof report !== "function") {
throw new TypeError("operation and report must be functions");
}
try {
signal?.throwIfAborted();
const value = await operation(signal);
signal?.throwIfAborted();
return { status: "ok", value };
} catch (reason) {
if (signal?.aborted && reason === signal.reason) return { status: "cancelled", reason };
if (reason instanceof InputError) return { status: "invalid", field: reason.field, code: reason.code };
let reportingFailed = false;
try { await report({ kind: "operation-failed" }); }
catch { reportingFailed = true; }
return { status: "failed", reason, reportingFailed };
}
}
const events = [];
const report = async event => { events.push(event); };
const object = { id: "kept" };
const ok = await runOperation(async () => object, { report });
console.log(ok.status, ok.value === object, events.length);
const invalid = await runOperation(() => { throw new InputError("email", "required"); }, { report });
console.log(invalid.status, invalid.field, invalid.code, events.length);
for (const reason of [undefined, false]) {
const failed = await runOperation(async () => { throw reason; }, { report });
console.log(failed.status, failed.reason === reason, failed.reportingFailed);
}
const original = new Error("private details stay out of the event");
const reporting = await runOperation(() => { throw original; }, { report: async () => { throw new Error("report failed"); } });
console.log(reporting.status, reporting.reason === original, reporting.reportingFailed);
const controller = new AbortController(), reason = { cancelled: true };
controller.abort(reason);
let starts = 0;
const cancelled = await runOperation(() => { starts++; }, { report, signal: controller.signal });
console.log(cancelled.status, cancelled.reason === reason, starts);
const otherController = new AbortController();
const unrelated = new Error("unrelated");
const other = await runOperation(() => { otherController.abort(reason); throw unrelated; }, { report, signal: otherController.signal });
console.log(other.status, other.reason === unrelated);
console.log(JSON.stringify(events));
// ✅ Expected output:
// ok true 0
// invalid email required 0
// failed true false
// failed true false
// failed true true
// cancelled true 0
// failed true
// [{"kind":"operation-failed"},{"kind":"operation-failed"},{"kind":"operation-failed"}]Reference notes
The Error.cause reference documents retained causal data. MDN’s unhandledrejection reference describes the global observation event. These examples test explicit result contracts, not a guarantee that an application can recover from every failure.
Practice quiz
What does this complete program print? async function run(){try{throw undefined}catch(reason){return {status:"failed",reason}}}const result=await run();console.log(result.status,Object.hasOwn(result,"reason"));
- failed true
- ok false
- failed false
- ok true
Answer: failed true. The explicit failure tag remains meaningful when the reason is undefined.
What does this complete program print? const original=new Error("original");const wrapped=new Error("context",{cause:original});console.log(wrapped===original,wrapped.cause===original);
- true true
- false true
- false false
- true false
Answer: false true. Wrapping creates a new error while cause retains the original identity.
What does this complete program print? const reports=[];try{try{throw new Error("one")}catch(error){reports.push("inner");throw error}}catch{reports.push("outer")}console.log(reports.length);
- 0
- 1
- 2
- 3
Answer: 2. Both catch blocks report the same propagated failure.
What does this complete program print? const controller=new AbortController(),cancel={id:1},bug={id:2};controller.abort(cancel);console.log(controller.signal.aborted&&bug===controller.signal.reason);
- true
- undefined
- TypeError
- false
Answer: false. An unrelated reason is not identified as cancellation by this contract.
What does this complete program print? const rows=[];const result={status:"ok",value:rows};console.log(result.status,result.value.length);
- ok 0
- failed 0
- ok undefined
- failed undefined
Answer: ok 0. A successful empty collection is distinct from an operation failure.
What does this complete program print? const effects=[];try{await Promise.all([Promise.resolve().then(()=>effects.push("saved")),Promise.reject("failed")])}catch{}console.log(effects.join(","));
- failed
- saved
- undefined
- rolled back
Answer: saved. Aggregation does not undo the other operation’s effect.
What does this complete program print? class InputError extends Error{}const error=new InputError("changed message");console.log(error instanceof InputError);
- false
- undefined
- true
- TypeError
Answer: true. Classification by the owned class does not depend on the message wording.
What does this complete program print? const original={id:1};let current;try{throw original}catch(reason){try{throw new Error("report failed")}catch{}current=reason}console.log(current===original);
- false
- undefined
- TypeError
- true
Answer: true. The separate reporter catch leaves the original failure available.
Continue this course
- Previous: Building Custom APIs with Fetch & Async Logic
- Next: Regular Expressions Advanced Techniques — Master lookaheads, named groups, and real-world regex patterns
- Quick reference: JavaScript cheat sheet