0
0
JavascriptHow-ToBeginner · 3 min read

How to Use Try Catch with Async Await in JavaScript

Use try and catch blocks around await expressions inside an async function to handle errors. This lets you write asynchronous code that looks like synchronous code and catch errors cleanly.
📐

Syntax

The try block contains the code that might throw an error, including await calls. The catch block handles any errors thrown inside the try. This pattern must be inside an async function.

javascript
async function example() {
  try {
    const result = await someAsyncFunction();
    console.log(result);
  } catch (error) {
    console.error('Error caught:', error);
  }
}
💻

Example

This example shows how to fetch data from a URL using fetch with async/await and handle errors using try catch. If the fetch fails, the error is caught and logged.

javascript
async function fetchData() {
  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log('Data received:', data);
  } catch (error) {
    console.error('Fetch error:', error.message);
  }
}

fetchData();
Output
Data received: { userId: 1, id: 1, title: "...", body: "..." }
⚠️

Common Pitfalls

One common mistake is forgetting to use try catch around await, which causes unhandled promise rejections. Another is using catch outside an async function or not awaiting the async call, which prevents catching errors properly.

javascript
async function wrongExample() {
  // This will NOT catch the error because no try catch
  const data = await Promise.reject(new Error('Oops'));
}

wrongExample().catch(error => console.log('Caught outside:', error.message));

// Correct way:
async function rightExample() {
  try {
    const data = await Promise.reject(new Error('Oops'));
  } catch (error) {
    console.log('Caught inside:', error.message);
  }
}
rightExample();
Output
Caught outside: Oops Caught inside: Oops
📊

Quick Reference

Remember these tips when using try catch with async await:

  • Always use try catch inside async functions to handle errors.
  • Use await to pause execution until the promise resolves or rejects.
  • Throw errors explicitly if needed to trigger catch.
  • Handle both network and logical errors inside catch.

Key Takeaways

Use try catch blocks inside async functions to handle errors from await calls.
Always await promises to catch errors properly with try catch.
Throw errors explicitly to trigger catch blocks when needed.
Avoid unhandled promise rejections by wrapping await in try catch.
Use catch outside async functions only if you handle the returned promise.