w3resource

Error Handling in Async/Await Functions with Try...Catch in JavaScript


Error Handling in Async/Await:

Write a JavaScript program to demonstrate how to handle errors in async/await functions using try...catch.

Solution-1: Error Handling with try...catch in an Async Function

Code:

// Function simulating an asynchronous task
const asyncTask = (taskName, time, shouldFail = false) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (shouldFail) {
        reject(`Error in ${taskName}`); // Reject the promise if shouldFail is true
      } else {
        resolve(`${taskName} completed`); // Resolve the promise otherwise
      }
    }, time);
  });
};

// Function using try...catch to handle errors
const executeTask = async () => {
  try {
    const result1 = await asyncTask("Task 1", 1000, false); // Successful task
    console.log(result1);

    const result2 = await asyncTask("Task 2", 2000, true); // Failing task
    console.log(result2); // This won't execute if Task 2 fails
  } catch (error) {
    console.error("Caught an error:", error); // Handle the error
  } finally {
    console.log("Execution finished"); // Always executes
  }
};

// Run the function
executeTask();

Output:

"Task 1 completed"
"Caught an error:"
"Execution finished"

Explanation:

  • asyncTask simulates an asynchronous operation and optionally fails.
  • executeTask calls asyncTask and handles potential errors using try...catch.
  • Errors are logged in the catch block, while the finally block ensures cleanup.

Solution-2: Error Handling in Multiple Tasks

Code:

// Function simulating an asynchronous task
const asyncTask = (taskName, time, shouldFail = false) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (shouldFail) {
        reject(`Error in ${taskName}`); // Reject if failure is triggered
      } else {
        resolve(`${taskName} completed`); // Resolve otherwise
      }
    }, time);
  });
};

// Function handling errors individually for each task
const executeTasks = async () => {
  try {
    const result1 = await asyncTask("Task 1", 1000, false); // Task 1 succeeds
    console.log(result1);
  } catch (error) {
    console.error("Error in Task 1:", error); // Handle error for Task 1
  }

  try {
    const result2 = await asyncTask("Task 2", 2000, true); // Task 2 fails
    console.log(result2);
  } catch (error) {
    console.error("Error in Task 2:", error); // Handle error for Task 2
  }

  console.log("Finished executing tasks"); // Executes regardless of task errors
};

// Run the function
executeTasks();

Output:

"Task 1 completed"
"Error in Task 2:"
"Finished executing tasks"

Explanation:

  • asyncTask is reused to simulate tasks with optional failure.
  • Each try...catch block handles errors individually for each task.
  • This approach isolates errors, ensuring that subsequent tasks still execute.

See the Pen promises-and-async-await-exercise-8 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Sequential Asynchronous tasks with Async/Await in JavaScript.
Next: Control Concurrent API Requests with JavaScript Throttling Techniques.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.