【发布时间】:2018-05-17 19:58:08
【问题描述】:
我需要通过fetch() 调用查询一些数据,但我不确定请求是否会成功,HTTP 方面:当服务器启动时,URL 可能(合法地)访问一个不存在的页面。
我想干净利落地处理此案,我目前的方法是引发异常:
// the URL is just an example, I did not have anything CORS-enabled (and unavailable) handy, thus the no-cors mode
fetch(`https://cdnjs.com/libraries/sdfsdfsfsdfsdfsdfdf`, {
mode: 'no-cors'
})
.then(r => {
if (!r.ok) {
console.log("page does not exist")
throw Error();
}
// if the page exists, it will return JSON data
return r.json();
})
.then(r => {
console.log(r)
// things with the JSON happen here
})
.catch(err => null)
我希望在Page does not exist 之后只返回return,但是(空)返回会被下一个then() 捕获。
当请求的 URL 不可用时,这是退出 fetch() 的正确方法吗?
【问题讨论】:
-
您希望在每种情况下如何处理这些数据?即,如果你得到 JSON,你想对它做什么,如果有错误你想做什么?
标签: javascript error-handling fetch-api