/**
* Wraps a function that processes a list of URLs to handle errors gracefully.
*
* @param {function} processUrl - The function to process each URL. Should accept a URL as input.
* @param {Array<string>} urls - An array of URLs to process.
* @returns {Array<object>} - An array of objects, each containing the URL and either its result or an error message.
*/
function wrapUrlList(processUrl, urls) {
if (!Array.isArray(urls)) {
throw new TypeError("urls must be an array");
}
const results = [];
for (const url of urls) {
if (typeof url !== 'string') {
results.push({ url: url, error: "Invalid URL: Must be a string." });
continue;
}
try {
const result = processUrl(url);
results.push({ url: url, result: result });
} catch (error) {
results.push({ url: url, error: error.message }); // Capture and store the error message
}
}
return results;
}
Add your comment