纯静态页面(无后端代理,HTML + JS 直接部署在 CDN/GitHub Pages 上)需要通过浏览器端 JavaScript 直接调用第三方 API。这种架构面临几个固有风险:
纯静态页面(无后端代理,HTML + JS 直接部署在 CDN/GitHub Pages 上)需要通过浏览器端 JavaScript 直接调用第三方 API。这种架构面临几个固有风险:
浏览器 fetch 默认没有超时。一个慢请求可以永久挂起页面功能。
async function fetchWithTimeout(url, timeoutMs = 8000) {
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
try {
const r = await fetch(url, { signal: ctrl.signal });
clearTimeout(timer);
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return r.json();
} catch (e) {
clearTimeout(timer);
throw e;
}
}使用 Promise.all 时,任何一个 promise reject 会导致整体失败。改为每个请求独立 catch:
const [dataA, dataB] = await Promise.all([
fetchWithTimeout(urlA).catch(() => null),
fetchWithTimeout(urlB).catch(() => null),
]);
// dataA 失败不影响 dataB 的结果不要用一个大的 try/catch 包裹多个功能模块:
// ❌ 错误:loadA 抛异常则 loadB、loadC 都不执行
try {
await loadA();
await loadB();
await loadC();
} catch (e) { /* 只捕获一个,丢失两个 */ }
// ✅ 正确:各自独立执行
loadA().catch(() => {});
loadB().catch(() => {});
loadC().catch(() => {});不要把原始错误信息(TypeError: Failed to fetch、HTTP 403)直接展示给用户:
// 区分常见的错误类型
if (e instanceof TypeError && e.message.includes('aborted')) {
return '请求超时,请检查网络后重试';
}
if (e.message?.includes('403')) {
return 'API 频率限制,请稍后刷新重试';
}
return '数据加载失败,已使用缓存显示';静态页面直接消费第三方 API 时,容错不是可选项而是架构必选项。因为没有后端中间层兜底,每个接口调用都直接暴露在浏览器环境下:
English:
lessons/en/static-page-github-api-fault-tolerance.md