I want to display error message from my API, problem is that I can\'t reach that error if I check for response.ok
, it returns Fetch error, not the one from API..
according to This Article :
Per MDN, the
fetch()
API only rejects a promise when“a network error is encountered, although this usually means permissions issues or similar.”
Basically
fetch()
will only reject a promise if the user is offline, or some unlikely networking error occurs, such a DNS lookup failure.
then, you can use this part of code to use non-network error handlings and make your code more readable
function handleErrors(response) {
if (!response.ok) throw new Error(response.status);
return response;
}
fetch("API URL")
// handle network err/success
.then(handleErrors)
// use response of network on fetch Promise resolve
.then(response => console.log("ok") )
// handle fetch Promise error
.catch(error => console.log(error) );