2

JavaScript fetch API doesn't returns proper error text if URL is incorrect. It always returns fail to fetch error in catch statement.

window.onload = () => {
  fetch("https://www.w3schools.com/nodejs/incorrecturl")
    .then(res => res.json())
    .then(data => console.log(data))
    .catch(error => alert(error.toString())) // Here i need proper error message, instead of "failed to fetch".
}
Shanmu_92
  • 835
  • 1
  • 7
  • 20
  • 1
    Why not just alert a custom message rather than the error it returns? – Snel23 May 23 '19 at 05:47
  • but how can i find that is incorrect url. If it returns 404 or 500 error means i can identify. – Shanmu_92 May 23 '19 at 06:08
  • @shanmu_92 you are not getting server error because the server is not configured of using a web service. if you want to see the error then you need to download the extension on google chrome browser *Allow-Control-Allow-Origin* add your URL in this extension. then run your script then you get a proper server error. Thanks – Sanat Gupta May 23 '19 at 06:52
  • By running your code snippet i am getting this error `unexpected end of json input` – Zabih Ullah May 23 '19 at 07:21

1 Answers1

1

Try this

var myRequest = new Request('https://www.w3schools.com/nodejs/incorrecturl');
fetch(myRequest).then(function(response) {
    console.log(response.status);
});

OR

fetch('https://www.w3schools.com/nodejs/incorrecturl').then(function(response) {
    console.log(response.status);
});

refs: https://developer.mozilla.org/en-US/docs/Web/API/Response/status