我只是很困惑什么是正确的方法,我在 react 中获取代码如下:
fetch(
`api_url`,
)
.then(response => response.json())
.then(
successResponse => {
...
},
errorResponse => {
...
}
)
或者我应该使用下面这个?我应该把 .catch 放在哪里?
fetch(
`api_url`,
)
.then(response => response.json())
// put .catch() here?
.then(
successResponse => {
...
}
)
.catch(errorResponse => {
...
}
)
两者有区别吗?我喜欢第一个,这两个捕获错误有不同吗?
最佳答案
如果您担心 response.json()
调用失败,只需在第一个 .then
调用中抛出一个新错误即可。
fetch(`api_url`)
.then((response) => {
if (response.ok) return response.json()
else throw new Error(`Could not fetch: ${response}`)
})
.then((successResponse) => {
...
})
.catch((errorResponse) => {
console.log(errorResponse)
})
关于javascript - 那么在获取时正确处理错误捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61109841/