javascript - 如果 URL 不正确,fetch API 不会在 catch 中显示确切的错误

标签 javascript promise try-catch fetch

如果 URL 不正确,JavaScript fetch API 不会返回正确的错误文本。它总是在 catch 语句中返回 fail to fetch 错误。

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

最佳答案

试试这个

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

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

关于javascript - 如果 URL 不正确,fetch API 不会在 catch 中显示确切的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56268679/

相关文章:

javascript - 将 req 数据传递到 Q Promise

javascript - Promise 返回值不正确

javascript - AngularJS promise ,$q,延迟

java - 异常情况下的返回语句

javascript - 网速慢时如何显示基本的html页面?

javascript - 无需物理文件即可从 Html 页面下载表格内容(字符串)

Javascript:将数组作为可选方法参数传递

php - 使 <div> 出现在当前滚动位置

php - 在文件未上传的 PHP 中尝试 catch 语句

c++ - 使用try-catch C++处理文件