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".
}

5
  • 1
    Why not just alert a custom message rather than the error it returns? Commented May 23, 2019 at 5:47
  • but how can i find that is incorrect url. If it returns 404 or 500 error means i can identify. Commented May 23, 2019 at 6: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 Commented May 23, 2019 at 6:52
  • By running your code snippet i am getting this error unexpected end of json input Commented May 23, 2019 at 7:21
  • I have the exact same problem. In dev tools an error mentioning net::ERR_NAME_NOT_RESOLVED turns up but that is not returned either from catch nor in the response Commented Jan 29, 2024 at 19:20

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

What script error do you get exactly? This is also how I handle things in my app. @shanmu_92
Uncaught (in promise) TypeError: Failed to fetch @BhanwarChaudhary
-1

You need to catch the error

fetch('https://www.w3schools.com/nodejs/incorrecturl')
 .then((response) => { console.log(response.status); })
 .catch((error) => { console.error('Request failed:', error); });

1 Comment

OP already is using .catch()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.