教程 axios tutorial

错误处理与超时机制对比

在前端开发中,了解不同请求库的错误处理和超时机制至关重要,Axios 与 Fetch 在这方面存在显著差异。

一、Axios 的错误处理

  • HTTP 状态码非 2xx 时抛出错误:
js
axios.get('/api/data')
  .then(res => console.log(res.data))
  .catch(err => {
    console.error(err.response?.status, err.message);
  });
  • 网络错误与超时:
js
axios.get('/api/data', { timeout: 5000 })
  .catch(err => {
    if (err.code === 'ECONNABORTED') console.warn('请求超时');
  });
  • 拦截器统一处理:
js
axios.interceptors.response.use(
  res => res,
  err => {
    console.error('请求出错:', err.message);
    return Promise.reject(err);
  }
);

二、Fetch 的错误处理

  • 仅对网络错误或请求被阻止抛出异常:
js
fetch('/api/data')
  .then(res => {
    if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
    return res.json();
  })
  .catch(err => console.error(err));
  • Fetch 默认不支持超时,需手动实现:
js
function fetchWithTimeout(url, timeout = 5000) {
  return Promise.race([
    fetch(url),
    new Promise((_, reject) => setTimeout(() => reject(new Error('请求超时')), timeout))
  ]);
}

三、主要差异总结

特性 Axios Fetch
HTTP 非 2xx 错误处理 自动抛出错误,可在 catch 捕获 不抛出,需要手动检查 res.ok
网络错误处理 catch 捕获 catch 捕获
超时设置 支持 timeout 配置 不支持,需手动实现
请求/响应拦截器 内置支持,可全局统一处理 无内置拦截器,需要封装

四、选择建议

  • Axios:适合需要统一错误处理、超时控制、请求拦截的项目,API 简单,兼容性好。
  • Fetch:原生浏览器 API,轻量但需自行处理错误和超时,适合小型项目或只需简单请求。

五、小结

理解 Axios 与 Fetch 的错误处理与超时机制差异,能够帮助前端开发者设计稳定可靠的接口调用逻辑,并结合项目需求选择最适合的方案。