1. /**
  2. * Wraps API endpoint calls to handle errors and provide quick fixes.
  3. * Uses a simple error handler for minimal memory footprint.
  4. *
  5. * @param {function} apiCall - The API call function. Should return a Promise.
  6. * @param {string} endpointName - A descriptive name for the endpoint.
  7. * @returns {function} - A wrapped function that handles errors.
  8. */
  9. function wrapApiCall(apiCall, endpointName) {
  10. return async function (...args) {
  11. try {
  12. const result = await apiCall(...args); // Execute the API call
  13. return result;
  14. } catch (error) {
  15. // Simple error handling - log and return a default value or error message
  16. console.error(`Error in ${endpointName}:`, error);
  17. return { error: "API request failed. Please check your credentials and network connection." }; //Provide a user-friendly error
  18. }
  19. };
  20. }
  21. // Example Usage (Illustrative)
  22. // async function fetchData() {
  23. // const response = await fetch('/api/data');
  24. // if (!response.ok) {
  25. // throw new Error(`HTTP error! Status: ${response.status}`);
  26. // }
  27. // return await response.json();
  28. // }
  29. // const wrappedFetchData = wrapApiCall(fetchData, 'fetchData'); // Wrap the fetchData function
  30. // async function callAPI(){
  31. // try{
  32. // const data = await wrappedFetchData();
  33. // console.log(data);
  34. // } catch (err){
  35. // console.error("Error in main function:", err.message);
  36. // }
  37. // }

Add your comment