/**
* Safely processes strings, handling potential errors gracefully.
*
* @param {string} str The string to process.
* @param {function} processString A function to apply to the string. Takes the string as input and returns a result or throws an error.
* @returns {Promise<string|null>} A promise that resolves with the result of the processing or null if an error occurred.
*/
async function safeStringProcess(str, processString) {
try {
// Attempt to process the string
const result = await processString(str);
return result; // Return the result if successful
} catch (error) {
console.error("Error processing string:", error);
return null; // Return null to indicate failure
}
}
// Example usage:
/**
* Simulates a string processing function that might fail.
* @param {string} str
* @returns {Promise<string>}
*/
async function exampleProcess(str) {
if (str.length < 5) {
throw new Error("String too short!");
}
return str.toUpperCase();
}
// Test case
async function runTest() {
const result = await safeStringProcess("hello", exampleProcess);
console.log("Result:", result); // Expected: HELLO
const result2 = await safeStringProcess("hi", exampleProcess);
console.log("Result2:", result2); // Expected: null
const result3 = await safeStringProcess(123, exampleProcess);
console.log("Result3:", result3); // Expected: null
}
runTest();
Add your comment