1. /**
  2. * Fetches file contents with graceful fallback and error handling.
  3. *
  4. * @param {string} filePath The path to the file.
  5. * @param {function} fallbackFunction The function to execute if file loading fails.
  6. * @returns {Promise<string>} A promise that resolves with the file contents as a string.
  7. * Rejects if both file loading and fallback fail.
  8. */
  9. async function getFileContents(filePath, fallbackFunction) {
  10. try {
  11. // Attempt to fetch the file contents using fetch.
  12. const response = await fetch(filePath);
  13. if (!response.ok) {
  14. // Handle HTTP errors.
  15. throw new Error(`HTTP error! Status: ${response.status}`);
  16. }
  17. const text = await response.text();
  18. return text; // Return file contents as a string.
  19. } catch (error) {
  20. // Handle fetch errors.
  21. console.error(`Error fetching file: ${filePath}`, error);
  22. // Execute the fallback function.
  23. try {
  24. const fallbackResult = await fallbackFunction();
  25. if (fallbackResult !== undefined) {
  26. return fallbackResult; // Return fallback result if successful.
  27. } else {
  28. throw new Error("Fallback function returned undefined."); //Propagate fallback failure.
  29. }
  30. } catch (fallbackError) {
  31. // Handle fallback errors.
  32. console.error("Fallback function failed:", fallbackError);
  33. throw new Error(`File loading and fallback failed: ${filePath}`, fallbackError); //Propagate combined failure.
  34. }
  35. }
  36. }

Add your comment