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 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 the CRUD (create, read, update, delete) operation and the id does not exist then you will get an error.
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 a method that will send the result to the next 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.
That’s it for today.
Don’t forget to subscribe to get my weekly newsletter with amazing tips, tricks, and articles directly in your inbox here.