LearnFrenzy
Sign in Take a free test

Error Handling · Error Handling Coding Problems · Question 7

A bank transfer that rolls back on error in JavaScript Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

Implement transfer(from, to, amount) on an in-memory ledger: debit, then credit, and if anything fails after the debit, restore the original balances (rollback) and re-throw a TransferError with the cause.

Solution
main.js
class TransferError extends Error {
  constructor(message, options) { super(message, options); this.name = "TransferError"; }
}
const ledger = { asha: 5000, ravi: 1200, frozen: 300 };
const frozenAccounts = new Set(["frozen"]);

function transfer(from, to, amount) {
  const snapshot = { ...ledger };                       // for rollback
  try {
    if (!(amount > 0)) throw new RangeError("amount must be positive");
    if (ledger[from] < amount) throw new Error(`insufficient funds in ${from}`);
    ledger[from] -= amount;                             // step 1: debit
    if (!(to in ledger)) throw new Error(`unknown account ${to}`);
    if (frozenAccounts.has(to)) throw new Error(`${to} is frozen`);
    ledger[to] += amount;                               // step 2: credit
    return `moved ₹${amount} ${from} → ${to}`;
  } catch (e) {
    Object.assign(ledger, snapshot);                    // undo the partial debit
    throw new TransferError(`transfer of ₹${amount} failed`, { cause: e });
  }
}

for (const [f, t, amt] of [["asha", "ravi", 1500], ["ravi", "frozen", 200], ["ravi", "ghost", 100], ["ravi", "asha", 9999]]) {
  try {
    console.log(transfer(f, t, amt));
  } catch (e) {
    console.log(`${e.name}: ${e.message} (${e.cause.message})`);
  }
}
console.log(ledger);

Output Verified by running it on Node.js

moved ₹1500 asha → ravi
TransferError: transfer of ₹200 failed (frozen is frozen)
TransferError: transfer of ₹100 failed (unknown account ghost)
TransferError: transfer of ₹9999 failed (insufficient funds in ravi)
{ asha: 3500, ravi: 2700, frozen: 300 }

The failed transfers had already debited ravi; the catch restores the snapshot so money is never lost, then reports a domain error that keeps the technical cause.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links