🟢 EasyError Handling📖 Theory Question

How do you handle errors in async/await properly?

💡

Hint

try/catch, re-throw unexpected errors, never swallow silently

Full Answer

// Option 1: try/catch (most common)
async function fetchData() {
  try {
    const data = await api.get('/users');
    return data;
  } catch (err) {
    if (err.status === 404) handleNotFound();
    else throw err; // re-throw unexpected errors
  }
}

// Option 2: .catch() at call site
const data = await fetchData().catch(err => null);

// Option 3: go/to helper
const to = p => p.then(d => [null, d]).catch(e => [e, null]);
const [err, data2] = await to(fetchData());
💡 Always handle promise rejections — unhandled ones crash Node.js.

More Error Handling Questions

🟢 EasyHow do you create custom Error types in JavaScript?→🟢 EasyWhat is error propagation and when should you re-throw an error?→

Practice this in a timed sprint →

5 free questions, no signup required

âš¡ Start Sprint