How to Handle Error in Javascript Promise?

In JavaScript, Promises provide a way to work with asynchronous operations. When working with Promises, you often need to handle errors that might occur during the execution of these asynchronous operations. There are several ways to handle errors in Promises:

Using catch() method

You can chain a catch() method to a Promise to handle any errors that might occur.

new Promise((resolve, reject) => {
    // some async operation
    reject(new Error("Something went wrong"));
})
.then(result => {
    // handle successful result
    console.log(result);
})
.catch(error => {
    // handle error
    console.error(error.message);
});

Using then() with two arguments

The then() method can take two arguments: the first one is a callback for a successful result, and the second one is a callback for errors.

new Promise((resolve, reject) => {
    // some async operation
    reject(new Error("Something went wrong"));
})
.then(
    result => {
        // handle successful result
        console.log(result);
    },
    error => {
        // handle error
        console.error(error.message);
    }
);

Using async/await with try/catch

If you’re using the async/await syntax, you can handle errors using the traditional try/catch approach.

async function asyncFunction() {
    try {
        let result = await someAsyncOperation();
        console.log(result);
    } catch (error) {
        console.error(error.message);
    }
}

asyncFunction();

Uncaught Promise errors

If you do not handle Promise rejections, they will be treated as unhandled promise rejections. Depending on the environment, an unhandled promise rejection might not crash the application but it’s generally considered bad practice to leave them unhandled.

To catch unhandled promise rejections globally, you can listen to the unhandledrejection event:

window.addEventListener('unhandledrejection', event => {
    console.warn(`Uncaught Promise Rejection: ${event.reason}`);
});

Using Promise.allSettled()

When working with multiple promises and you want to know the status of each promise whether it’s fulfilled or rejected, you can use Promise.allSettled():

const promise1 = Promise.resolve(3);
const promise2 = new Promise((resolve, reject) => setTimeout(reject, 100, 'foo'));

Promise.allSettled([promise1, promise2])
    .then(results => results.forEach(result => {
        if (result.status === "fulfilled") {
          console.log(result.value);
      } else {
            console.error(result.reason);
        }
    }));

Remember, always handle errors in your Promises to ensure that your applications are robust and provide useful feedback to users or developers.