Examining the Core Problem
I've just begun dissecting the user's implicit needs, focusing on the assumed pattern of repetitive fetch calls. My initial assessment centers on identifying the root cause behind these redundant requests, which the user clearly wants to eliminate. I'm already anticipating potential solutions like caching or a more streamlined data retrieval strategy.
Defining the Solution's Scope
I'm now outlining a reusable function to replace the repetitive fetch calls. The focus is error handling and common request needs, like parsing JSON responses. I am thinking of the user's need for a clean, easy-to-use tool to streamline API interactions.
Crafting a Generic Solution
I'm now structuring the fetchRequest function. I will ensure error messages include status codes and implement basic JSON parsing by default, whilst keeping it configurable. I'm prioritizing flexibility for diverse API responses, considering text and blob handling down the line. Error reporting is key, and I want a clean interface.
Optimizing for Practical Use
I'm now iterating on the fetchRequest function. I've added default headers for JSON content and improved error handling by parsing JSON responses to get more informative error messages. I'm also ensuring the function re-throws errors for easier handling by the calling code. I feel this makes it more robust.
Enhancing Function Flexibility
I'm now integrating content type checks to handle non-JSON responses gracefully. The next refinement involves distinguishing between GET and POST parameters for better readability and cleaner function calls. I'm focusing on ensuring robust error messages, incorporating server-side details. I am now working on usage examples.
Improving Error Reporting Further
I'm now prioritizing the accuracy of error messages. I'm considering using response.text() as a fallback when response.json() fails to extract more specific server-side details. The aim is to surface the most relevant information to the user in the error messages. Usage examples will also include specific failure scenarios.
Here is a robust, reusable utility function. It handles repetitive tasks like setting headers, checking status codes, parsing JSON, and surfacing API-specific error messages.
The Utility Function (api.js)
/**
* reliableFetch - A generic wrapper around the native fetch API.
*
* @param {string} url - The URL to request.
* @param {Object} options - Fetch options (method, body, headers, etc.).
* @returns {Promise<any>} - The parser JSON response data.
*/
export async function reliableFetch(url, options = {}) {
// 1. Set default headers (e.g., for sending JSON)
const defaultHeaders = {
'Content-Type': 'application/json',
// Add 'Authorization': 'Bearer ...' here if needed globally
};
// 2. Merge defaults with user-provided options
const config = {
...options,
headers: { ...defaultHeaders, ...options.headers },
};
try {
const response = await fetch(url, config);
// 3. Check if the response is JSON
const isJson = response.headers.get('content-type')?.includes('application/json');
const data = isJson ? await response.json() : null;
// 4. check for HTTP error status (404, 500, etc.)
if (!response.ok) {
// Prefer the API's error message, fallback to status text
const errorMsg = (data && data.message) || response.statusText;
throw new Error(`API Error: ${errorMsg} (${response.status})`);
}
return data;
} catch (error) {
// 5. Handle Network errors or Parsing errors
console.error('Fetch operation failed:', error);
throw error; // Re-throw so the calling component can handle it
}
}
How to use it
Here is a comparison of the "Old Repetitive Way" versus the "Refactored Way."
1. GET Request
The Old Way:
// ❌ Repetitive
try {
const res = await fetch('https://api.example.com/users');
if (!res.ok) throw new Error('Failed');
const data = await res.json();
console.log(data);
} catch (e) {
console.error(e);
}
The New Way:
// ✅ Clean
import { reliableFetch } from './api';
async function getUsers() {
try {
const users = await reliableFetch('https://api.example.com/users');
console.log(users);
} catch (error) {
// Handle UI error state here
}
}
2. POST Request (Sending Data)
The Old Way:
// ❌ Repetitive headers and stringify
const res = await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Alice' })
});
const data = await res.json();
The New Way:
// ✅ Automatic headers, just pass the config
const newUser = await reliableFetch('https://api.example.com/users', {
method: 'POST',
body: JSON.stringify({ name: 'Alice' })
});
Key Improvements in this solution:
- Centralized Header Management: You don't have to type
Content-Type: application/json in every single request.
- Automatic Error Extraction: Standard
fetch does not throw an error on HTTP 400/500 errors. This wrapper checks response.ok automatically.
- Smart Error Messages: If your server returns
{ message: "Invalid Email" } with a 400 error, this wrapper extracts that specific message (data.message) instead of just saying "Bad Request".
- Safe JSON Parsing: It checks if the header is actually JSON before trying to parse it (preventing unexpected crashes if the server returns HTML/Text).