The Fetch API is not that new and most developers have used it at some point to retrieve resources from a server, but do you really know how to handle errors when using this API?
Given the code below, in which a request using the Fetch API returns a 404 error, what would be the message in the console: successful or failed?
try{// this endpoint will return 404constresponse=awaitfetch('https://restcountries.com/v4.1/all');console.log('Success');}catch{console.error('Failed');
In short, the Fetch API is an interface for easily making asynchronous HTTP GET and POST requests to endpoints.
I'm assuming you're familiar with promises in JavaScript and know how they work (because one of the reasons the Fetch API is so popular is because it returns a promise). Therefore, we can use the power of then, catch and finally when the fetch is resolved, rejected and finished.
Wrapping the fetch call in a try/catch block is a very common way of handling errors (see example below), but not all errors can be caught and I will explain this just after the code.
try{// this endpoint will return CORS errorconstresponse=awaitfetch('https://google.com/api');}catch{console.error('Failed');// Output: FailedEnter fullscreen modeExit fullscreen modenetwork errors: failure to connect to the server which can be caused by several reasons, such as slow network and timeout, for example.
CORS errors: when a domain is not authorised to obtain resources from a different domain.
Fetch will return resolved for server status errors (like 404 and 500 for instance), that's the reason why catch can't get them in the example at the beginning of this article.
// this endpoint will return 404constresponse=awaitfetch('https://restcountries.com/v4.1/all');if (response.ok){// ...do something with the response if response.ok is true}else{console.error('Failed');Enter fullscreen modeExit fullscreen mode
try{constresponse=awaitfetch('https://restcountries.com/v4.1/all');if (response.ok){console.log('Promise resolved and HTTP status is successful');// ...do something with the response}else{console.error('Promise resolved but HTTP status failed');}catch{console.error('Promise rejected');Enter fullscreen modeExit fullscreen modeconstresponse=awaitfetch('https://restcountries.com/v4.1/all');if (response.ok){console.log('Promise resolved and HTTP status is successful');// ...do something with the response}else{// Custom message for failed HTTP codesif (response.status===404)thrownewError('404, Not found');if (response.status===500)thrownewError('500, internal server error');// For any other server errorthrownewError(response.status);}catch (error){console.error('Fetch',error);// Output e.g.: "Fetch Error: 404, Not found"Enter fullscreen modeExit fullscreen mode
Here we throw errors to handle them in the catch block and also display a custom message in the console depending on the type of error.
when response.ok returns false, we can simple throw an error, so the catch block will be executed
catch will then handle all types of errors
catch accepts an argument that can be customized when throwing errors from the try block
response.status can be used to check the returned HTTP status code to display customized messages in the console (like 400, 404, 500…).
It is very important to handle all errors that may occur when using Fetch API when retrieving resources from the server and here I have explained how to use try/catch along with response.ok and response.status to get different errors and also customize the way we are dealing with them.
See you next time! 😁
Hey, If you’re talking about the last code snippet (example 2), this is the explanation: after checking if the error is 404 or 500, we need a way to check any other kind of failed response, which can be done by using ‘!response.ok’. So, if the server returns 400, for example, this code will throw an error as well. For 404 and 500, we display customized messages, that’s the reason we use ‘response.status’ for them.
Please, let me know if I answered your question, otherwise I’d like you provide me with more detail about which example you are talking about.
// if(!response.ok) throw new Error(response.status) // redundant if-clause.
throw new Error(response.status)
Enter fullscreen modeExit fullscreen mode
It gets really interesting when you get the more unusual response codes like 3xx or 1xx. Should you trust the automated redirect or look at the location header yourself?
In case of 1xx -> should you poll for results? The fetch API supports all this, so the ball is firmly in your application logic’s court
Built on Forem — the open source software that powers DEV and other inclusive communities.