1. /**
  2. * Safely processes strings, handling potential errors gracefully.
  3. *
  4. * @param {string} str The string to process.
  5. * @param {function} processString A function to apply to the string. Takes the string as input and returns a result or throws an error.
  6. * @returns {Promise<string|null>} A promise that resolves with the result of the processing or null if an error occurred.
  7. */
  8. async function safeStringProcess(str, processString) {
  9. try {
  10. // Attempt to process the string
  11. const result = await processString(str);
  12. return result; // Return the result if successful
  13. } catch (error) {
  14. console.error("Error processing string:", error);
  15. return null; // Return null to indicate failure
  16. }
  17. }
  18. // Example usage:
  19. /**
  20. * Simulates a string processing function that might fail.
  21. * @param {string} str
  22. * @returns {Promise<string>}
  23. */
  24. async function exampleProcess(str) {
  25. if (str.length < 5) {
  26. throw new Error("String too short!");
  27. }
  28. return str.toUpperCase();
  29. }
  30. // Test case
  31. async function runTest() {
  32. const result = await safeStringProcess("hello", exampleProcess);
  33. console.log("Result:", result); // Expected: HELLO
  34. const result2 = await safeStringProcess("hi", exampleProcess);
  35. console.log("Result2:", result2); // Expected: null
  36. const result3 = await safeStringProcess(123, exampleProcess);
  37. console.log("Result3:", result3); // Expected: null
  38. }
  39. runTest();

Add your comment