/**
* Wraps API endpoint calls to handle errors and provide quick fixes.
* Uses a simple error handler for minimal memory footprint.
*
* @param {function} apiCall - The API call function. Should return a Promise.
* @param {string} endpointName - A descriptive name for the endpoint.
* @returns {function} - A wrapped function that handles errors.
*/
function wrapApiCall(apiCall, endpointName) {
return async function (...args) {
try {
const result = await apiCall(...args); // Execute the API call
return result;
} catch (error) {
// Simple error handling - log and return a default value or error message
console.error(`Error in ${endpointName}:`, error);
return { error: "API request failed. Please check your credentials and network connection." }; //Provide a user-friendly error
}
};
}
// Example Usage (Illustrative)
// async function fetchData() {
// const response = await fetch('/api/data');
// if (!response.ok) {
// throw new Error(`HTTP error! Status: ${response.status}`);
// }
// return await response.json();
// }
// const wrappedFetchData = wrapApiCall(fetchData, 'fetchData'); // Wrap the fetchData function
// async function callAPI(){
// try{
// const data = await wrappedFetchData();
// console.log(data);
// } catch (err){
// console.error("Error in main function:", err.message);
// }
// }
Add your comment