// Reusable async/await fetch utility with comprehensive error handling
async function apiFetch(url, options = {}) {
try {
const config = {
headers: {
'Content-Type': 'application/json',
...options.headers,
},
...options,
};
const response = await fetch(url, config);
if (!response.ok) {
// Attempt to parse error details from response
let errorData;
try {
errorData = await response.json();
} catch {
errorData = { message: response.statusText };
}
throw new Error(
`API request failed: ${response.status} ${response.statusText} - ${errorData.message || 'Unknown error'}`
);
}
// Auto-detect and parse JSON, text, or blob based on Content-Type
const contentType = response.headers.get('content-type');
if (contentType?.includes('application/json')) {
return await response.json();
} else if (contentType?.includes('text/')) {
return await response.text();
} else {
return await response.blob();
}
} catch (error) {
// Log for debugging (customize as needed, e.g., integrate with Sentry)
console.error(`[API Fetch Error] ${url}:`, error.message);
// Re-throw with context for caller to handle (e.g., show toast, retry)
throw new Error(`Fetch failed for ${url}: ${error.message}`);
}
}
// Usage example (replaces repetitive fetch calls):
// Instead of:
// const user = await fetch('/api/users/123').then(r => r.json()).catch(console.error);
// Use:
try {
const userData = await apiFetch('/api/users/123');
const postData = await apiFetch('/api/posts', { method: 'POST', body: JSON.stringify({ title: 'New Post' }) });
} catch (error) {
// Handle error uniformly (e.g., show user-friendly message)
alert(error.message);
}