Middle+
What ways are there to handle errors in Promise? Can try/catch be used?
sobes.tech AI
Answer from AI
In JavaScript, there are several ways to handle errors in Promises:
- The
.catch()method — the most common way to handle errors:
fetch('url')
.then(response => response.json())
.catch(error => {
console.error('Error:', error);
});
- The second argument in
.then(onFulfilled, onRejected)— you can pass an error handling function:
promise.then(
result => { /* handle result */ },
error => { /* handle error */ }
);
- Using
async/awaitwithtry/catch:
async function fetchData() {
try {
const response = await fetch('url');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
Important: The try/catch block cannot be used directly around a promise.then() call to catch errors inside the promise. try/catch works with await or synchronous code. If you use try/catch without await, errors in promises will not be caught.
Summary:
- To handle errors in promises, you can use
.catch()or the second argument of.then(). - For
async/await, usetry/catch. - You cannot use
try/catchto handle errors in promises withoutawait.