/**
* Extends task queue logic with debugging and graceful failure handling.
*
* @param {Array<Function>} queue - The task queue (array of functions).
* @param {function} errorCallback - Callback function to handle task failures.
* @returns {function} - A modified queue with debugging capabilities.
*/
function enhanceTaskQueue(queue, errorCallback) {
if (!Array.isArray(queue)) {
console.error("Queue must be an array.");
return function(task) {
errorCallback("Invalid queue provided");
};
}
if (typeof errorCallback !== 'function') {
console.error("Error callback must be a function.");
return function(task) {
errorCallback("Invalid error callback");
};
}
const enhancedQueue = [...queue]; // Create a copy to avoid modifying the original
enhancedQueue.forEach((task, index) => {
const originalTask = task; // Store the original task
task = function (...args) {
console.debug(`Executing task at index ${index} with arguments:`, args);
try {
const result = originalTask(...args); // Execute the original task
console.debug(`Task at index ${index} completed successfully. Result:`, result);
return result;
} catch (error) {
console.error(`Task at index ${index} failed:`, error);
errorCallback(error); // Call the error callback
return undefined; // Or handle the error appropriately (e.g., re-queue)
}
};
enhancedQueue[index] = task; // Replace the original task with the enhanced version
});
return enhancedQueue;
}
/**
* Example usage (for testing/demonstration)
*/
// const myQueue = [
// (x) => x * 2,
// (x) => { throw new Error("Simulated error"); },
// (x) => x + 1
// ];
//
// const handleErrors = (error) => {
// console.error("Error occurred:", error);
// };
//
// const enhancedQueue = enhanceTaskQueue(myQueue, handleErrors);
//
// enhancedQueue.forEach(task => {
// task(5);
// });
Add your comment