JavaScript Handling Errors in async/await Explained

JavaScript Logo

Handling Errors in async/await – Use `try/catch` to handle errors in async functions when using `await`.

๐Ÿ‘‰ Syntax

try {
  const data = await fetch();
} catch (err) {
  // handle error
}

๐Ÿงช Example

async function getData() {
  try {
    let res = await fetch('/bad');
  } catch (e) {
    console.error('Failed:', e);
  }
}

Comments