I’m having some problems trying to understand the following code in an excercise concerning error handling:
const getSuggestions = () => {
const wordQuery = inputField.value;
const endpoint = url + wordQuery;
fetch(endpoint, {cache: 'no-cache'})
.then(response => {
if(response.ok) {
return response.json();
} throw new Error('Request failed!');
}, networkError => {
console.log(networkError.message);
})
}
My question is: Why do we catch errors for two times here? One time using throw new Error
, and one time by adding a second argument networkError
into .then()
? Are they catching the same error and thus redundant?
How does it look if we use try...catch...
here?
3
Answers
Because fetch will only throw an error on network errors, not on error status-codes like 404.
In this snippet Someone checked wether the response was 200 and if not added a “custom” error using throw.
This is equivalent code, but hopefully more understandable
The 2 error mechanisms are dealing with different types of errors:
if(!response.ok) deals with http responses from the server for http 4xx and 5xx response statuses. The call reached an http server and it responded.
The networkError => { is for errors arising before even reaching a server, possibly even reaching the network.
They are very different, managed differently.