如果网址不正确,fetch API不会在catch中显示确切错误

时间:2019-05-23 05:39:44

标签: javascript promise try-catch fetch

如果URL不正确,

JavaScript 获取API 不会返回正确的错误文本。它总是在 catch 语句中返回无法获取错误。

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

1 个答案:

答案 0 :(得分:1)

尝试

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);
});

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