ZBLOG

fetch如何捕获失败?

在 JavaScript 中,使用 fetch 捕获请求失败需要区分两种类型的“失败”:


1. 网络错误(Network Error)

当请求无法到达服务器(如断网、跨域失败、URL 错误等),fetch 会直接抛出异常。需用 .catch() 捕获:

  1. fetch('https://api.example.com/data')
  2. .then(response => {
  3. if (!response.ok) {
  4. throw new Error(`HTTP error! status: ${response.status}`);
  5. }
  6. return response.json();
  7. })
  8. .catch(error => {
  9. console.error('Request failed:', error); // 捕获网络错误或解析异常
  10. });

2. HTTP 错误状态码(如 404、500)

fetch 不会自动将 HTTP 错误状态码(如 404、500)视为失败,需要手动检查 response.ok

  1. fetch('https://api.example.com/not-found')
  2. .then(response => {
  3. if (!response.ok) {
  4. throw new Error(`HTTP error! status: ${response.status}`); // 主动抛出错误
  5. }
  6. return response.json();
  7. })
  8. .catch(error => {
  9. console.error('Request failed:', error); // 捕获 HTTP 错误
  10. });

完整示例

  1. fetch('https://api.example.com/data')
  2. .then(response => {
  3. if (!response.ok) throw new Error(`HTTP ${response.status}`);
  4. return response.json();
  5. })
  6. .then(data => console.log(data))
  7. .catch(error => {
  8. console.error('Failed:', error); // 统一处理网络/HTTP/解析错误
  9. });

关键点总结

  • fetch 只有网络层失败才会触发 catch,HTTP状态码需通过 response.ok判断。
  • throw 将 HTTP错误转为能被.catch()捕获的异常
  • 兼容性:旧浏览器可能需要 polyfill(如 whatwg-fetch)。

如果需要更简洁的错误处理,可以考虑封装工具函数或使用库(如 axios)。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=23243

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?