Understanding and Handling Promise Rejection Errors in JavaScript

Learn what promise rejection errors are in JavaScript and how to handle them effectively with practical examples for beginners.

Promises are an important feature in JavaScript for handling asynchronous operations like fetching data from an API or reading files. Sometimes, these promises fail and get "rejected." Understanding how to handle these promise rejections is crucial for building error-resilient applications.

A promise can be in one of three states: pending, fulfilled, or rejected. When a promise is rejected, it means an error or unexpected situation occurred during the async operation.

Let's start with a simple example of creating a promise that rejects:

javascript
const myPromise = new Promise((resolve, reject) => {
  reject('Something went wrong!');
});

If you run this promise without handling rejection, you may get an unhandled promise rejection warning or error. To handle rejected promises, you can use either `.catch()` after the promise or use `async/await` with try/catch blocks.

Here's how to catch rejected promises using `.catch()`:

javascript
myPromise
  .then(result => {
    console.log('Success:', result);
  })
  .catch(error => {
    console.error('Error caught:', error);
  });

The `.catch()` method receives the rejection reason (error) and lets you handle it gracefully instead of the app crashing or showing unwanted warnings.

If you are using `async/await`, you handle promise rejections using a try/catch block as shown below:

javascript
async function fetchData() {
  try {
    const data = await myPromise;
    console.log('Data:', data);
  } catch (error) {
    console.error('Caught error with async/await:', error);
  }
}

fetchData();

Using try/catch with async/await provides a clean way to handle promise rejections especially when working with multiple asynchronous operations.

In summary, always handle rejected promises either by chaining `.catch()` or using try/catch when working with async/await. This prevents unhandled promise rejections and allows your app to recover or show friendly error messages.

By practicing proper error handling, you make your JavaScript applications more stable and easier to debug.