w3resource

Effective error handling in JavaScript Promises


Handling Promise Rejection:

Write a JavaScript program that demonstrates how to catch and handle errors in Promises using .catch().

Solution-1: Using .catch() Directly

Code:

// Create a Promise that rejects after a delay
const delayedRejection = new Promise((resolve, reject) => {
  setTimeout(() => {
    reject("An error occurred!"); // Reject the Promise with an error message
  }, 1000); // Delay of 1 second
});

// Handle the Promise and catch the rejection
delayedRejection
  .then((result) => {
    console.log("This will not be logged:", result); // Will not execute because the Promise rejects
  })
  .catch((error) => {
    console.error("Caught an error:", error); // Logs the rejection message
  });

Output:

Caught an error:
An error occurred!

Explanation:

  • A Promise is created using new Promise, which rejects with an error message after 1 second.
  • .then() is added to handle successful resolution, but it does not execute because the Promise rejects.
  • .catch() is used to catch and handle the rejection, logging the error message to the console.

Solution-2: Using try...catch with async/await

Code:

// Create an asynchronous function to handle the Promise
async function handleRejection() {
  try {
    // Await a Promise that will reject after 1 second
    const result = await new Promise((resolve, reject) => {
      setTimeout(() => {
        reject("Async error occurred!"); // Reject the Promise
      }, 1000);
    });

    console.log("This will not be logged:", result); // Will not execute because the Promise rejects
  } catch (error) {
    console.error("Caught an error in async/await:", error); // Logs the rejection message
  }
}

// Call the asynchronous function
handleRejection(); 

Output:

"Caught an error in async/await:"

Explanation:

  • An asynchronous function is defined using async to handle the Promise.
  • Inside the function, the await keyword is used to wait for the resolution of a Promise.
  • If the Promise rejects, control moves to the catch block where the error is logged.
  • This approach makes error handling more structured and easier to follow in asynchronous code.

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


Improve this sample solution and post your code through Disqus

Previous: How to use Promise chains for Sequential Async tasks?
Next: JavaScript Promise.any Explained with simple examples.

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.