Fetch API Wrapper dengan Error Handling
JavaScript
#javascript
#fetch
#api
#async
Wrapper ringan untuk Fetch API dengan timeout, retry, dan error handling.
async function api(url, options = {}) {
const { timeout = 10000, retries = 2, ...fetchOpts } = options;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeout);
const defaultHeaders = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.content || '',
};
const config = {
credentials: 'same-origin',
...fetchOpts,
headers: { ...defaultHeaders, ...fetchOpts.headers },
signal: controller.signal,
};
for (let attempt = 0; attempt <= retries; attempt++) {
try {
const response = await fetch(url, config);
clearTimeout(timer);
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new Error(body.message || `HTTP ${response.status}`);
}
return await response.json();
} catch (err) {
if (attempt === retries || err.name === 'AbortError') {
throw err;
}
await new Promise(r => setTimeout(r, 1000 * (attempt + 1)));
}
}
}
// Usage
const data = await api('/api/posts', { method: 'GET' });
await api('/api/posts', { method: 'POST', body: JSON.stringify({ title: 'Hello' }) });
187 views
12 copies
1 hari yang lalu