I am following a tutorial about handling errors of fetch() but now it turns to be learning handling errors. This is the code I wrote. I wish to handle all errors inside the outer catch:
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
name: this.enteredName,
rating: this.chosenRating
}
}).then(response => {
if (response.ok) {
//...
} else {
response.json().then(json => {
const msg = 'Custom error handling: could not save data' +
', error code: ' + response.status + ', error: ' + json.error;
throw new Error(msg);
}).catch(e => {
console.log('catch1:');
throw e;
});
}
})
.catch(err => {
console.log('catch2:');
this.error = err.message;
});
The problem with this code is that the outer catch cannot catch the error from inner then block, even through I rethrow it in inner catch block. What would be a clean and elegant way to achieve this? Please dont change response.ok because I wish to learn the solution for this exact situation.
By using
return Promise.reject(e);in the inner catch block, you ensure that the rejected promise is propagated down the chain, allowing the outercatchblock to handle the error. This way, you don't need to rethrow the error in the outer catch block, and it will be caught by the outer catch block as intended.