Files
J-Board-Lite/src/lib/fetch-with-timeout.ts
2026-04-29 05:16:29 +10:00

30 lines
697 B
TypeScript

export class TimeoutError extends Error {
constructor(message: string) {
super(message);
this.name = "TimeoutError";
}
}
export async function fetchWithTimeout(
input: RequestInfo | URL,
init: RequestInit = {},
timeoutMs = 10_000,
): Promise<Response> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), timeoutMs);
try {
return await fetch(input, {
...init,
signal: init.signal ?? controller.signal,
});
} catch (error) {
if (error instanceof Error && error.name === "AbortError") {
throw new TimeoutError("请求超时");
}
throw error;
} finally {
clearTimeout(timeout);
}
}