/**
* Safely processes a string, handling potential errors with fallback logic.
*
* @param {string} str The string to process.
* @param {function} primaryProcessor A function to process the string.
* @param {function} fallbackProcessor A function to execute if primaryProcessor fails.
* @returns {any} The result of the primary processor, or the result of the fallback processor if the primary fails.
*/
function safeStringProcessor(str, primaryProcessor, fallbackProcessor) {
try {
// Attempt to process the string with the primary processor.
return primaryProcessor(str);
} catch (error) {
// If the primary processor fails, execute the fallback processor.
console.warn("Primary processor failed. Using fallback."); // Log a warning
return fallbackProcessor(str);
}
}
//Example Usage:
/**
* A sample primary processor - converts to uppercase.
*/
function primaryExample(str) {
if (typeof str !== 'string') {
throw new Error("Input must be a string");
}
return str.toUpperCase();
}
/**
* A sample fallback processor - returns the original string.
*/
function fallbackExample(str) {
return str;
}
// Test case
const result1 = safeStringProcessor("hello", primaryExample, fallbackExample);
console.log(result1); // Output: HELLO
const result2 = safeStringProcessor(123, primaryExample, fallbackExample);
console.log(result2); // Output: 123 (fallback logic)
const result3 = safeStringProcessor("world", () => "processed", () => "error");
console.log(result3); // Output: processed
Add your comment