1. /**
  2. * Safely processes a string, handling potential errors with fallback logic.
  3. *
  4. * @param {string} str The string to process.
  5. * @param {function} primaryProcessor A function to process the string.
  6. * @param {function} fallbackProcessor A function to execute if primaryProcessor fails.
  7. * @returns {any} The result of the primary processor, or the result of the fallback processor if the primary fails.
  8. */
  9. function safeStringProcessor(str, primaryProcessor, fallbackProcessor) {
  10. try {
  11. // Attempt to process the string with the primary processor.
  12. return primaryProcessor(str);
  13. } catch (error) {
  14. // If the primary processor fails, execute the fallback processor.
  15. console.warn("Primary processor failed. Using fallback."); // Log a warning
  16. return fallbackProcessor(str);
  17. }
  18. }
  19. //Example Usage:
  20. /**
  21. * A sample primary processor - converts to uppercase.
  22. */
  23. function primaryExample(str) {
  24. if (typeof str !== 'string') {
  25. throw new Error("Input must be a string");
  26. }
  27. return str.toUpperCase();
  28. }
  29. /**
  30. * A sample fallback processor - returns the original string.
  31. */
  32. function fallbackExample(str) {
  33. return str;
  34. }
  35. // Test case
  36. const result1 = safeStringProcessor("hello", primaryExample, fallbackExample);
  37. console.log(result1); // Output: HELLO
  38. const result2 = safeStringProcessor(123, primaryExample, fallbackExample);
  39. console.log(result2); // Output: 123 (fallback logic)
  40. const result3 = safeStringProcessor("world", () => "processed", () => "error");
  41. console.log(result3); // Output: processed

Add your comment