1. /**
  2. * Extends task queue logic with debugging and graceful failure handling.
  3. *
  4. * @param {Array<Function>} queue - The task queue (array of functions).
  5. * @param {function} errorCallback - Callback function to handle task failures.
  6. * @returns {function} - A modified queue with debugging capabilities.
  7. */
  8. function enhanceTaskQueue(queue, errorCallback) {
  9. if (!Array.isArray(queue)) {
  10. console.error("Queue must be an array.");
  11. return function(task) {
  12. errorCallback("Invalid queue provided");
  13. };
  14. }
  15. if (typeof errorCallback !== 'function') {
  16. console.error("Error callback must be a function.");
  17. return function(task) {
  18. errorCallback("Invalid error callback");
  19. };
  20. }
  21. const enhancedQueue = [...queue]; // Create a copy to avoid modifying the original
  22. enhancedQueue.forEach((task, index) => {
  23. const originalTask = task; // Store the original task
  24. task = function (...args) {
  25. console.debug(`Executing task at index ${index} with arguments:`, args);
  26. try {
  27. const result = originalTask(...args); // Execute the original task
  28. console.debug(`Task at index ${index} completed successfully. Result:`, result);
  29. return result;
  30. } catch (error) {
  31. console.error(`Task at index ${index} failed:`, error);
  32. errorCallback(error); // Call the error callback
  33. return undefined; // Or handle the error appropriately (e.g., re-queue)
  34. }
  35. };
  36. enhancedQueue[index] = task; // Replace the original task with the enhanced version
  37. });
  38. return enhancedQueue;
  39. }
  40. /**
  41. * Example usage (for testing/demonstration)
  42. */
  43. // const myQueue = [
  44. // (x) => x * 2,
  45. // (x) => { throw new Error("Simulated error"); },
  46. // (x) => x + 1
  47. // ];
  48. //
  49. // const handleErrors = (error) => {
  50. // console.error("Error occurred:", error);
  51. // };
  52. //
  53. // const enhancedQueue = enhanceTaskQueue(myQueue, handleErrors);
  54. //
  55. // enhancedQueue.forEach(task => {
  56. // task(5);
  57. // });

Add your comment