0
0
Javascriptprogramming~5 mins

Error handling with async and await in Javascript

Choose your learning style9 modes available
Introduction

We use error handling with async and await to catch problems when waiting for tasks that take time, like loading data from the internet. It helps keep the program running smoothly without crashing.

When fetching data from a website or API and you want to handle if the website is down.
When reading files or databases asynchronously and need to manage errors like missing files.
When calling any function that returns a promise and you want to catch errors cleanly.
When you want to show a friendly message if something goes wrong during a long task.
When debugging to find out why an async task failed.
Syntax
Javascript
async function example() {
  try {
    const result = await someAsyncTask();
    // use result here
  } catch (error) {
    // handle error here
  }
}

The async keyword makes a function return a promise and allows using await inside it.

The try...catch block is used to catch errors that happen during the awaited task.

Examples
This example fetches data from a website and catches errors if the fetch fails.
Javascript
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
This example shows catching a rejected promise error inside an async function.
Javascript
async function waitAndFail() {
  try {
    await Promise.reject(new Error('Oops!'));
  } catch (error) {
    console.log('Caught error:', error.message);
  }
}
Sample Program

This program waits for a promise that gives the number 42 and prints it. If there was an error, it would print the error instead.

Javascript
async function getNumber() {
  try {
    const number = await Promise.resolve(42);
    console.log('Number is', number);
  } catch (error) {
    console.log('Error:', error);
  }
}

getNumber();
OutputSuccess
Important Notes

Always use try...catch inside async functions to handle errors gracefully.

Without try...catch, errors in awaited promises can crash your program or go unnoticed.

You can also use .catch() on promises, but try...catch with async/await looks cleaner and is easier to read.

Summary

Use async and await to write asynchronous code that looks like normal code.

Wrap awaited calls in try...catch to catch and handle errors.

This helps keep your program running smoothly and makes debugging easier.