Junior — Middle
How can you track and handle an error that occurs when using a promise in the rejected state?
sobes.tech AI
Answer from AI
To track and handle errors when using a promise in the rejected state, you can use the .catch() method or the second argument of the .then() method.
Example using .catch():
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
return Promise.reject('Network error');
}
return response.json();
})
.then(data => {
console.log('Data:', data);
})
.catch(error => {
console.error('An error occurred:', error);
});
You can also use try...catch inside an asynchronous function with await:
async function getData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) {
throw new Error('Network error');
}
const data = await response.json();
console.log('Data:', data);
} catch (error) {
console.error('An error occurred:', error);
}
}
getData();
Thus, error handling in the rejected state allows for proper response to failures and prevents application crashes.