在 JavaScript 中,使用 fetch
捕获请求失败需要区分两种类型的“失败”:
1. 网络错误(Network Error)
当请求无法到达服务器(如断网、跨域失败、URL 错误等),fetch
会直接抛出异常。需用 .catch()
捕获:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.catch(error => {
console.error('Request failed:', error); // 捕获网络错误或解析异常
});
2. HTTP 错误状态码(如 404、500)
fetch
不会自动将 HTTP 错误状态码(如 404、500)视为失败,需要手动检查 response.ok
:
fetch('https://api.example.com/not-found')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`); // 主动抛出错误
}
return response.json();
})
.catch(error => {
console.error('Request failed:', error); // 捕获 HTTP 错误
});
完整示例
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then(data => console.log(data))
.catch(error => {
console.error('Failed:', error); // 统一处理网络/HTTP/解析错误
});
关键点总结
fetch
只有网络层失败才会触发catch
,HTTP状态码需通过response.ok
判断。throw
将 HTTP错误转为能被.catch()
捕获的异常。- 兼容性:旧浏览器可能需要 polyfill(如
whatwg-fetch
)。
如果需要更简洁的错误处理,可以考虑封装工具函数或使用库(如 axios
)。
内容由零声教学AI助手提供,问题来源于学员提问