fetch 很好用,但有幾個行為和直覺不同,沒處理好就會出現「請求失敗了畫面卻沒反應」的問題。
HTTP 錯誤不會被 catch
try {
const res = await fetch('/api/users');
const data = await res.json(); // 500 時這裡可能拿到錯誤頁 HTML 而解析失敗
} catch (err) {
// 只有網路錯誤、CORS 失敗、被取消時才會進來
}
要自己檢查 res.ok:
const res = await fetch('/api/users');
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
逾時
const res = await fetch('/api/report', {
signal: AbortSignal.timeout(8000),
});
逾時時會拋出 name 為 TimeoutError 的錯誤。
取消過時的請求
搜尋框每打一個字就發一次請求,舊的回應可能比新的晚回來,蓋掉正確的結果:
let controller;
input.addEventListener('input', async () => {
controller?.abort();
controller = new AbortController();
try {
const res = await fetch(`/api/search?q=${encodeURIComponent(input.value)}`, {
signal: controller.signal,
});
render(await res.json());
} catch (err) {
if (err.name !== 'AbortError') showError(err);
}
});
整合成一個工具函式
export async function request(url, { timeout = 10000, retries = 2, ...options } = {}) {
for (let attempt = 0; ; attempt++) {
try {
const res = await fetch(url, { ...options, signal: AbortSignal.timeout(timeout) });
if (res.ok) return res.status === 204 ? null : res.json();
// 4xx 是請求本身的問題,重試也沒用
if (res.status < 500 || attempt >= retries) {
throw Object.assign(new Error(`HTTP ${res.status}`), { status: res.status });
}
} catch (err) {
if (err.status || attempt >= retries) throw err;
}
await new Promise((r) => setTimeout(r, 300 * 2 ** attempt)); // 300ms、600ms…
}
}
CAUTION
只對冪等的請求自動重試(GET、PUT、DELETE)。POST 重試可能造成重複下單,除非後端支援 Idempotency-Key。
給使用者看得懂的訊息
| 情況 | 建議訊息 |
|---|---|
| 網路錯誤 | 「連線中斷,請檢查網路後再試一次。」 |
| 逾時 | 「伺服器回應太慢,請稍後再試。」 |
| 401 | 導向登入頁 |
| 5xx | 「系統暫時有問題,我們正在處理。」 |
發表留言