Async Error Handling

Promises and async/await

Example

const request = (ok) => new Promise((res, rej) =>
  setTimeout(() => (ok ? res("data") : rej(new Error("503 Service Unavailable"))), 10));

request(false).catch((e) => console.log("promise catch:", e.message));

(async () => {
  try {
    await request(false);
  } catch (e) {
    console.log("try/catch:", e.message);
  }
})();

Output

promise catch: 503 Service Unavailable
try/catch: 503 Service Unavailable

Unhandled Rejections and Retries

Example

A rejected promise nobody handles is reported as an error (and crashes Node). A small retry helper for flaky network calls:

let attempts = 0;
const flaky = () => new Promise((res, rej) => (++attempts < 3 ? rej(new Error("fail " + attempts)) : res("ok on attempt " + attempts)));

async function retry(fn, times = 3) {
  for (let i = 1; i <= times; i++) {
    try { return await fn(); }
    catch (e) { console.log("attempt", i, "failed:", e.message); if (i === times) throw e; }
  }
}
retry(flaky).then(console.log);

Output

attempt 1 failed: fail 1
attempt 2 failed: fail 2
ok on attempt 3