Error handling with promises
When working with promises in JavaScript, it’s important to handle errors appropriately to ensure that your application remains robust and error-free. Here are some techniques for error handling with promises:
Use the catch() method: The catch() method is used to catch any errors that occur during the execution of a promise chain. It takes a callback function as its argument, which is called if any of the promises in the chain are rejected.
asyncFunction()
.then(result => {
// Do something with the result
})
.catch(error => {
// Handle the error
});
Use the finally() method: The finally() method is used to run code after the promise chain has completed, whether it resolved or rejected. This can be useful for cleanup or logging purposes.
asyncFunction()
.then(result => {
// Do something with the result
})
.catch(error => {
// Handle the error
})
.finally(() => {
// Do something after the promise chain completes
});
Throw an error in the promise chain: If an error occurs in the promise chain, you can throw an error to reject the promise and pass the error to the catch() method.
asyncFunction()
.then(result => {
if (result === null) {
throw new Error('Result is null');
}
// Do something with the result
})
.catch(error => {
// Handle the error
});
Return a rejected promise: If an error occurs in the promise chain, you can return a rejected promise to pass the error to the catch() method.
asyncFunction()
.then(result => {
if (result === null) {
return Promise.reject(new Error('Result is null'));
}
// Do something with the result
})
.catch(error => {
// Handle the error
});
By using these techniques, you can ensure that your promises are robust and reliable, and that your application handles errors gracefully.