Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 26 - Error Handling in Async/Await

When using async/await, handling errors properly is crucial. JavaScript provides try...catch to manage errors in asynchronous functions.


Explanation

  • Errors in an async function can be caught using try...catch.
  • The catch block handles any rejected Promises or unexpected errors.
  • It prevents the program from crashing when an error occurs.

Example 1: Handling Errors with try...catch

async function fetchData() {
    try {
        let response = await fetch("https://invalid.url/api/data");
        let data = await response.json();
        console.log(data);
    } catch (error) {
        console.error("Error fetching data:", error.message);
    }
}

fetchData();
  • The catch block captures the error and logs a meaningful message instead of crashing the program.

Example 2: Rejecting a Promise and Catching the Error

function fetchData() {
    return new Promise((resolve, reject) => {
        setTimeout(() => reject(new Error("Failed to fetch data")), 1500);
    });
}

async function getData() {
    try {
        let data = await fetchData();
        console.log(data);
    } catch (error) {
        console.error("Error:", error.message);
    }
}

getData();
  • If fetchData() fails, the catch block prevents an uncaught error.

Try Your Hand

Steps:

  1. Create a File:

    • Name it day27-error-handling.html.
  2. Write the Code:

    • Copy the following code:

      <!DOCTYPE html>
      <html lang="en">
      <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Day 27 - Error Handling</title>
      </head>
      <body>
      <script>
         async function fetchData() {
             try {
                 let response = await fetch("https://invalid.url/api/data");
                 let data = await response.json();
                 console.log(data);
             } catch (error) {
                 console.error("Error fetching data:", error.message);
             }
         }
      
         fetchData();
      </script>
      </body>
      </html>
  3. Save the File.

  4. Open Developer Console (F12) to See the Error Message.


Experiment

  1. Modify fetchData() to use a valid URL and see if it works.
  2. Simulate an error inside try and observe how catch handles it.

Key Takeaways

  • try...catch prevents crashes in async functions.
  • Errors should be handled gracefully with user-friendly messages.
  • Always use catch when working with asynchronous code.