How to handle errors in a Promise?
How to handle errors in a Promise?
261
26-Sep-2023
Updated on 26-Sep-2023
Aryan Kumar
26-Sep-2023To handle 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:
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():
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.