Перейти до основного вмісту
← ⚡ JavaScript & the browser·Модуль C7 · Урок 6
ЗавданняWrite async function loadOrFallback(p) that takes a Promise p. In try/catch: return await p on success; in catch log 'fallback: ' + err.message and return 0. Call it with Promise.resolve(42) (log result) and Promise.reject(new Error('down')) (log result).

Async errors — try/catch around await

125 XP9 min
Теорія

try/catch wraps awaits naturally

An await inside try/catch behaves exactly like a synchronous throw. If the awaited Promise rejects, the catch catches it.

async function loadUser(id) {
  try {
    const r = await fetch(`/api/users/${id}`);
    if (!r.ok) throw new Error("HTTP " + r.status);
    return await r.json();
  } catch (err) {
    console.error("loadUser failed:", err);
    return null;
  }
}

fetch + the HTTP-error trap

fetch only rejects on network errors. A 404 response does NOT reject — the Promise fulfills, you have to check r.ok (or status code) yourself. Forgetting this is the #1 fetch bug.

const r = await fetch("/api/x");
if (!r.ok) throw new Error(`HTTP ${r.status}`);

Returning vs throwing

return null from a catch turns "missing data" into a checkable value. throw propagates to the caller. Pick based on whether the caller should handle it.

🔒

Зареєструйся щоб кодувати

Теорія відкрита всім. Інтерактивний редактор, живий перегляд і перевірка відкриваються з 7-денним безкоштовним trial — потрібна картка, скасування у будь-який час.

Реєстрація — безкоштовний trial →

Перші 10 уроків у кожному треку — безкоштовні. Картка не потрібна.

← НазадНаступний урок →

Отримуй одну пораду з Python чи вебу — щодня поштою

Коротко, без води, без спаму. Відписка — в один клік.