网络并不总是可靠。请求可能因为断网、服务端错误或响应过慢而失败。一个健壮的请求函数需要区分错误类型,并给用户明确的反馈。
本节要点
- fetch 只在网络层失败时 reject,HTTP 500 仍会进入 then。
- AbortController 可以主动取消请求,也可以实现超时。
- 重试只适合幂等请求,并且要控制次数和间隔。
- 向用户展示错误时,避免直接暴露服务端堆栈信息。
可运行示例
示例封装了带超时的 fetch,并对失败请求自动重试两次。可以先测试正常请求,再测试服务端错误。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>超时与重试</title>
</head>
<body>
<h1>超时与重试</h1>
<button id="ok">正常请求</button>
<button id="fail">服务端错误</button>
<button id="slow">超时请求</button>
<pre id="output"></pre>
<script>
const output = document.getElementById('output');
async function fetchWithTimeout(url, options = {}, timeout = 800) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
try {
return await fetch(url, { ...options, signal: controller.signal });
} finally {
clearTimeout(timer);
}
}
async function requestWithRetry(url, retries = 2) {
let lastError;
for (let attempt = 1; attempt <= retries + 1; attempt++) {
try {
const response = await fetchWithTimeout(url);
if (!response.ok) throw new Error('HTTP ' + response.status);
return await response.json();
} catch (error) {
lastError = error;
output.textContent += `第 ${attempt} 次失败:${error.name} ${error.message}\n`;
if (attempt <= retries) {
await new Promise(resolve => setTimeout(resolve, 300 * attempt));
}
}
}
throw lastError;
}
function run(url) {
output.textContent = '';
requestWithRetry(url)
.then(data => { output.textContent += '成功:' + JSON.stringify(data); })
.catch(error => { output.textContent += '最终失败:' + error.message; });
}
document.getElementById('ok').onclick = () => run('/ajax/demo/echo.php');
document.getElementById('fail').onclick = () => run('/ajax/demo/echo.php?fail=1');
document.getElementById('slow').onclick = () => run('/ajax/demo/echo.php?delay=3000');
</script>
</body>
</html>运行说明:三个按钮分别演示成功、500 错误和超时。超时按钮会在 800ms 时被 AbortController 中止,并触发两次重试。 在线运行示例 →
三类错误
| 类型 | 表现 | 处理方式 |
|---|---|---|
| 网络错误 | fetch reject,如断网、DNS 失败 | 提示检查网络,可重试 |
| HTTP 错误 | response.ok 为 false | 按状态码提示,4xx 通常不重试 |
| 业务错误 | HTTP 200,但 JSON 中 code 表示失败 | 读取业务码并提示具体原因 |
重试的边界
只对 GET 等幂等请求自动重试。POST 可能已经成功但响应丢失,盲目重试会造成重复下单或重复提交。
提示:AbortController 中止请求后,fetch 会抛出 name 为 AbortError 的异常,可以据此区分超时和普通失败。