繁体   English   中英

我如何处理获取 api 反应中的错误?

[英]how can i process error in 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 function 处理 fetch 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%20the%20fetch(),such%20a% 20DNS%20lookup%20 失败

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM