Fetch API 的错误处理机制是怎样的?与 Axios 相比,有哪些优缺点?
Fetch API 的错误处理主要基于 Promise 的机制。当使用 fetch 发起请求时,如果请求成功返回了响应,无论响应的状态码如何(比如 404,500 状态码),fetch 都会解析此响应为一个 Response 对象,并将 Promise resolve。只有当网络请求失败(例如连接超时,DNS 查询失败等)时,Promise 才会被 reject。这意味着对于 HTTP 错误状态码(如 404,500)需要额外处理。常见的做法是,在 fetch 调用后的 .then 方法中检查 Response 对象的 ok 属性,如果为 false,则手动抛出异常。示例如下:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
相比之下,Axios 的错误处理更加直观和符合直觉。Axios 在网络请求失败或接收到非 2xx 状态码的响应时,都会自动将 Promise reject,简化了错误处理的代码。此外,Axios 还提供了一个统一的接口来配置请求和响应拦截器,可以更方便地处理请求和响应数据、添加通用的请求头、统一处理错误等。示例如下:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
优缺点对比:
- 优点:
- Fetch API:它是现代浏览器原生支持的标准接口,不需要额外引入库。其基于流的响应处理(Response.Body)允许开发者开始读取数据流,甚至在接收完整个数据之前就开始处理。
- Axios:提供更丰富的功能和更好的错误处理机制,支持请求/响应拦截,自动转换请求数据为 JSON 等,且可以用于浏览器和 Node.js 环境。
- 缺点:
- Fetch API:默认情况下错误处理不够直接,处理状态码错误时需要额外的检查。在某些旧浏览器中可能需要 polyfill 支持。
- Axios:作为一个外部库,需要额外的资源加载,可能会增加项目的体积。