/* 带超时的 fetch(F6):所有业务接口统一走这里,弱网/挂起的请求不会永远占着按钮和遮罩。 * * - 默认 8000ms 超时,到期用 AbortController 掐断,抛出的 Error 带 name='AbortError'、timeout=true * - 调用方自己传了 signal 时沿用调用方的(不覆盖) * - 纯逻辑、无 DOM 依赖,可在 node 测试里直接跑 */ export const DEFAULT_FETCH_TIMEOUT_MS = 8000; export function makeTimeoutError(ms) { const err: any = new Error(`请求超时(${ms}ms 内没有响应)`); err.name = "AbortError"; err.timeout = true; return err; } /** * fetch + 超时。签名与原生 fetch 一致,多一个 ms。 * 注意:signal 一旦 abort,fetch 会 reject 一个 AbortError(浏览器原生);我们把它统一成带 timeout 标记的错误。 */ export function fetchWithTimeout(url: string, options: any = {}, ms: number = DEFAULT_FETCH_TIMEOUT_MS): Promise { const timeout = Number(ms) > 0 ? Number(ms) : DEFAULT_FETCH_TIMEOUT_MS; const opts = Object.assign({}, options); if (typeof AbortController === "undefined" || opts.signal) { return fetch(url, opts); } const ctrl = new AbortController(); opts.signal = ctrl.signal; const timer = setTimeout(() => ctrl.abort(), timeout); return fetch(url, opts).finally(() => clearTimeout(timer)).catch(err => { if (err && err.name === "AbortError" && ctrl.signal.aborted) throw makeTimeoutError(timeout); throw err; }); } /** 读 JSON:非 JSON 响应(网关错误页等)返回 null 而不是抛错,方便调用方区分 401/HTML。 */ export async function fetchJsonWithTimeout(url: string, options: any = {}, ms?: number) { const resp = await fetchWithTimeout(url, options, ms); let body: any = null; try { body = await resp.json(); } catch (e) { body = null; } return { resp, body, ok: !!body && typeof body === "object" }; }