-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsafe-fetch.js
More file actions
28 lines (23 loc) · 859 Bytes
/
Copy pathsafe-fetch.js
File metadata and controls
28 lines (23 loc) · 859 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// ==========================================
// Safe Fetch — fetch wrapper with timeout and error handling
// ==========================================
// All AI provider calls and outbound HTTP requests should use
// this instead of bare fetch() to ensure timeouts and error handling.
const DEFAULT_TIMEOUT_MS = 60000; // 60 seconds
export async function safeFetch(url, options = {}, timeoutMs = DEFAULT_TIMEOUT_MS) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(url, {
...options,
signal: controller.signal,
});
if (!res.ok) {
const body = await res.text().catch(() => '');
throw new Error(`HTTP ${res.status}: ${body.slice(0, 200)}`);
}
return await res.json();
} finally {
clearTimeout(timer);
}
}