/**
* Fetches file contents with graceful fallback and error handling.
*
* @param {string} filePath The path to the file.
* @param {function} fallbackFunction The function to execute if file loading fails.
* @returns {Promise<string>} A promise that resolves with the file contents as a string.
* Rejects if both file loading and fallback fail.
*/
async function getFileContents(filePath, fallbackFunction) {
try {
// Attempt to fetch the file contents using fetch.
const response = await fetch(filePath);
if (!response.ok) {
// Handle HTTP errors.
throw new Error(`HTTP error! Status: ${response.status}`);
}
const text = await response.text();
return text; // Return file contents as a string.
} catch (error) {
// Handle fetch errors.
console.error(`Error fetching file: ${filePath}`, error);
// Execute the fallback function.
try {
const fallbackResult = await fallbackFunction();
if (fallbackResult !== undefined) {
return fallbackResult; // Return fallback result if successful.
} else {
throw new Error("Fallback function returned undefined."); //Propagate fallback failure.
}
} catch (fallbackError) {
// Handle fallback errors.
console.error("Fallback function failed:", fallbackError);
throw new Error(`File loading and fallback failed: ${filePath}`, fallbackError); //Propagate combined failure.
}
}
}
Add your comment