如何处理fetch-api react中的错误



我在Reactjs组件中使用fetch发送api请求。但是在响应之后,它不会来进行阻塞。可能是一些错误作为回应。如果发生错误,我想重定向到错误页面

fetch('endpoint')
.then(r => { 
> what if response is not ok 
})

查看Promise捕获块:

fetch('https://no-such-server.blabla') // rejects
.then(response => response.json())
.catch(err => alert(err)) // Here is where you handle the error

参考:https://javascript.info/promise-error-handling

使用catch函数处理获取api 中的错误

fetch('endpoint')
.then(r => { 
// deal with response flow
})
.catch(err => {
console.error(err)
//> deal with error flow
})

有关详细信息,请参阅以下链接https://www.tjvantoll.com/2015/09/13/fetch-and-errors/#:~:text=Per%20MDN%2C%20fetch((,例如%20a%20DNS%20lookup%20失败。

最新更新