【问题标题】:Catching error in fetch() function在 fetch() 函数中捕获错误
【发布时间】:2018-06-28 14:53:32
【问题描述】:
我最近学习了一些关于 fetch() 和 promise 的知识,现在我需要在项目中使用它。这里我有一个 fetch() 函数,效果很好,但我认为,它必须捕获一个错误。那么,在 fetch() 函数中捕获错误的最佳方法是什么?我需要在 then() 中抓住它们?
这里有一些代码:
const endpoint = 'http://localhost:3030/api/hotels';
const promise = fetch(endpoint)
.then(res => res.json(), err => {
console.log(err);
})
.then(parseRooms, err => {
console.log(err);
})
谢谢!
【问题讨论】:
标签:
javascript
error-handling
fetch
es6-promise
fetch-api
【解决方案1】:
使用承诺处理程序链接在一起这一事实。对then 或catch 的每次调用都会创建一个新的promise,该promise 链接到前一个promise。
所以在你的情况下:
const promise = fetch(endpoint)
.then(res => res.json())
.then(parseRooms)
.catch(error => {
// Do something useful with the error
});
我假设parseRooms 如果接收到的结构有问题,则会引发错误。
您可能还想在其中检查res.ok,因为fetch 仅失败如果出现网络错误,而不是出现诸如404 之类的HTTP 错误: p>
const promise = fetch(endpoint)
.then(res => {
if (!res.ok) {
throw new Error(); // Will take you to the `catch` below
}
return res.json();
})
.then(parseRooms)
.catch(error => {
// Do something useful with the error
});