Handling Errors in Async Code

Tutorial 4 of 5

1. Introduction

In this tutorial, our goal is to understand how to handle errors effectively in asynchronous JavaScript code. We will be focusing on the use of try/catch blocks within promises and async/await syntax.

By the end of this tutorial, you will learn:

  • What asynchronous code is and why it's crucial in JavaScript.
  • How to use try/catch blocks within promises.
  • How to use try/catch with async/await syntax.

Prerequisites: Basic understanding of JavaScript and asynchronous programming.

2. Step-by-Step Guide

Asynchronous Code

JavaScript is single-threaded, which means it can only do one thing at a time. To overcome this limitation and avoid blocking the main thread, JavaScript uses asynchronous programming.

Promises and Try/Catch

A Promise is an object representing the eventual completion or failure of an asynchronous operation. To handle errors in promises, we can use .catch() method. However, using try/catch blocks can provide better error handling.

Consider this promise:

let promise = new Promise((resolve, reject) => {
    throw new Error('Promise failed!');
});

To handle the error, we can use try/catch as follows:

try {
    promise.catch(error => console.error(error));
} catch (error) {
    console.error('Caught:', error);
}

Async/Await and Try/Catch

Async/await syntax is a new and cleaner way to handle asynchronous operations. It makes asynchronous code look and behave like synchronous code.

Here's how you can use try/catch with async/await:

async function asyncFunction() {
    try {
        let response = await fetch('https://api.github.com/users/github');
        let user = await response.json();
        console.log(user.name);
    } catch (error) {
        console.error('Caught:', error);
    }
}

3. Code Examples

Example 1: Using Try/Catch With Promises

let promise = new Promise((resolve, reject) => {
    throw new Error('Promise failed!');
});

try {
    promise.catch(error => console.error(error)); // This will log: Error: Promise failed!
} catch (error) {
    console.error('Caught:', error);
}

In this example, we create a promise that immediately throws an error. We then use a try/catch block to catch any errors thrown by the promise.

Example 2: Using Try/Catch With Async/Await

async function asyncFunction() {
    try {
        let response = await fetch('https://api.github.com/users/github');
        let user = await response.json();
        console.log(user.name); // This will log: GitHub
    } catch (error) {
        console.error('Caught:', error);
    }
}
asyncFunction();

In this example, we define an async function that makes a fetch request to the GitHub API. It then tries to parse the response as JSON and log the user's name. If any of these operations fail, the catch block will log the error.

4. Summary

We've covered:

  • The importance of error handling in asynchronous JavaScript code.
  • How to use try/catch blocks with promises and async/await syntax.

To continue learning, you might want to explore:

  • More about Promises and Async/Await in JavaScript.
  • Other methods of error handling in JavaScript.

5. Practice Exercises

  1. Write an async function that fetches data from a URL and logs the data. Use try/catch to handle errors.

Solution:

async function fetchData(url) {
    try {
        let response = await fetch(url);
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Caught:', error);
    }
}
fetchData('https://api.github.com/users/github');
  1. Write a function that returns a promise that resolves after 2 seconds. Use try/catch to handle errors.

Solution:

function delay() {
    return new Promise(resolve => setTimeout(resolve, 2000));
}

try {
    delay().then(() => console.log('Resolved after 2 seconds'));
} catch (error) {
    console.error('Caught:', error);
}

Remember to always handle errors in your asynchronous code to ensure your application runs smoothly.