1. /**
  2. * Handles array operations with graceful failure.
  3. *
  4. * @param {Array} arr The array to operate on.
  5. * @param {function} operation The function to perform on the array.
  6. * @param {function} errorHandler A function to handle errors. Takes error object as argument.
  7. * @returns {Array|null} The result of the operation if successful, null if an error occurs.
  8. */
  9. function safeArrayOperation(arr, operation, errorHandler) {
  10. try {
  11. // Check if the input is an array
  12. if (!Array.isArray(arr)) {
  13. errorHandler("Input must be an array");
  14. return null;
  15. }
  16. // Check if the operation is a function
  17. if (typeof operation !== 'function') {
  18. errorHandler("Operation must be a function");
  19. return null;
  20. }
  21. const result = operation(arr);
  22. return result;
  23. } catch (error) {
  24. // Handle errors during the operation
  25. errorHandler(error);
  26. return null;
  27. }
  28. }
  29. // Example usage (demonstrates error handling)
  30. function exampleOperation(arr) {
  31. // Simulate a potential error
  32. if (arr.length === 0) {
  33. throw new Error("Array is empty");
  34. }
  35. return arr.map(x => x * 2);
  36. }
  37. function myErrorHandler(error) {
  38. console.error("Error occurred:", error.message);
  39. }
  40. // Test cases
  41. const myArray = [1, 2, 3, 4, 5];
  42. const result1 = safeArrayOperation(myArray, exampleOperation, myErrorHandler);
  43. console.log("Result 1:", result1); // Output: [2, 4, 6, 8, 10]
  44. const emptyArray = [];
  45. const result2 = safeArrayOperation(emptyArray, exampleOperation, myErrorHandler);
  46. console.log("Result 2:", result2); // Output: null
  47. const notAnArray = "hello";
  48. const result3 = safeArrayOperation(notAnArray, exampleOperation, myErrorHandler);
  49. console.log("Result 3:", result3); // Output: null
  50. const invalidOperation = "not a function";
  51. const result4 = safeArrayOperation(myArray, invalidOperation, myErrorHandler);
  52. console.log("Result 4:", result4); // Output: null

Add your comment