JavaScript Tutorial

JavaScript Error Handling

Source: Programming with Mosh

try / catch / retry

Real APIs fail — timeouts, 503s, rate limits. Production code retries with backoff and falls back to cached data.

Tip: Run this example twice. The sandbox returns intermittent 503 errors so you can practice retry logic.
JAVASCRIPT
async function loadWithRetry(fn, retries = 3) {
  for (let i = 1; i <= retries; i++) {
    try { return await fn(); }
    catch (e) { if (i === retries) throw e; await new Promise(r => setTimeout(r, i * 300)); }
  }
}
Weather API with retry backoff

Console

// Click Run — watch API traces and console output