Take a look at the below code:
fetch('https://jsonplaceholder.typicode.com/todos/4')
.then(response => response.json())
.then(result => console.log('success:',result))
.catch(error => console.log('error:', error));
Here, we’re making an API call to get a todo with id 4 and it will work
because there is a todo with id 4 But what If the id does not exist or the
server throws an error like 404 or 500 or any other error?
fetch('https://jsonplaceholder.typicode.com/todos/2382822')
.then(response => response.json())
.then(result => console.log('success:',result))
.catch(error => console.log('error:', error));
Here, we have provided a very large id that does not exist. But if you
execute in the browser console, you will see that a success message is
printed even though it’s clearly a 404 error.
Ideally, the .catch handler should be executed but that does not
happen in the case of fetch .
fetch only goes into .catch handler when it fails to make the
request for example when the network is not available or the domain
does not exist.
So If you’re using fetch for performing CRUD (create, read, update,
delete) operation and the id do not exist then you will get an error.
If you’re using fetch then you have to write a lot of extra code for
handling every HTTP status code error which is cumbersome.
So If you’re building a large scale application or you don’t want to
handle all HTTP status code errors, then use axios or superagent or
any other library instead of fetch .
Because in all of those libraries catch will be executed when there is
any type of error that is easy to handle rather than writing code for
every status code.
This is the reason, you will find code for fetch written like this:
fetch('https://jsonplaceholder.typicode.com/todos/4')
.then((response) => {
if (response.ok) {
return response.json();
}
return Promise.reject(response);
})
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log('Something went wrong.', error);
});
where inside the .then handler, we’re checking if the response is ok .
If the response is OK , we’re calling response.json() method which
will send the result to the next .then handler.
If the response is NOT OK, then we’re rejecting the promise so it will
call the .catch() handler to print the actual error.
I hope this article help you to understand something or improve yourself ! If you have any question ask me in comment !
Would be Happy to HELP! 😊
Top comments (2)
Would you mind making an Article about how to work with API in javascript, I'm new to this and it's cracking my head, I've searched for other articles but they are not explaining on the level of a beginner.
Sure, I will try to make an article for beginner as simple as possible.