---
title: "How to handle errors in a Promise?"  
description: "How to handle errors in a Promise?"  
author: "Sandra Emily"  
published: 2023-09-26  
updated: 2023-09-26  
canonical: https://www.mindstick.com/forum/159914/how-to-handle-errors-in-a-promise  
category: "javascript"  
tags: ["javascript", "promise"]  
reading_time: 2 minutes  

---

# How to handle errors in a Promise?

How to [handle errors](https://www.mindstick.com/forum/157886/how-do-you-handle-errors-and-exceptions-in-angularjs-applications) in a [Promise](https://www.mindstick.com/forum/158328/what-is-a-promise-in-javascript-and-how-do-you-use-it)?

## Replies

### Reply by Aryan Kumar

To [handle](https://www.mindstick.com/articles/311004/suede-skillet-handle-cover) [errors](https://answers.mindstick.com/qa/116170/fresh-fir-against-gandhis-in-national-herald-case-cover-up-for-ed-s-own-errors) in a Promise in JavaScript, you can use the **.catch()** method or the second argument of the **.then()** method. Both approaches allow you to specify a callback function that will be executed when the Promise is rejected (i.e., in the rejected state).

Here's how to handle errors using both methods:

**Using .catch() method**:

```plaintext
const myPromise = new Promise((resolve, reject) => {
  // Simulate a failed asynchronous operation
  setTimeout(() => {
    reject("Operation failed!"); // Reject the promise with an error
  }, 2000);
});

myPromise
  .then((result) => {
    // This function will not be called on rejection
    console.log("Success:", result);
  })
  .catch((error) => {
    // This function will be called when the Promise is rejected
    console.error("Error:", error);
  });
```

In this example, if **myPromise** is rejected (after a 2-second delay), the **.catch()** method's callback function is called, allowing you to handle the error.

**Using the second argument of .then()**:

```plaintext
const myPromise = new Promise((resolve, reject) => {
  // Simulate a failed asynchronous operation
  setTimeout(() => {
    reject("Operation failed!"); // Reject the promise with an error
  }, 2000);
});

myPromise
  .then((result) => {
    // This function will not be called on rejection
    console.log("Success:", result);
  })
  .catch((error) => {
    // This function will be called when the Promise is rejected
    console.error("Error:", error);
  });
```

You can use either approach to handle errors in a Promise. The key is to provide a rejection callback function that will be invoked when the Promise is rejected. Inside this callback, you can perform error handling tasks, such as logging the error, displaying an error message, or taking appropriate action based on the error.


---

Original Source: https://www.mindstick.com/forum/159914/how-to-handle-errors-in-a-promise

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
