1. /**
  2. * Wraps a function that processes a list of URLs to handle errors gracefully.
  3. *
  4. * @param {function} processUrl - The function to process each URL. Should accept a URL as input.
  5. * @param {Array<string>} urls - An array of URLs to process.
  6. * @returns {Array<object>} - An array of objects, each containing the URL and either its result or an error message.
  7. */
  8. function wrapUrlList(processUrl, urls) {
  9. if (!Array.isArray(urls)) {
  10. throw new TypeError("urls must be an array");
  11. }
  12. const results = [];
  13. for (const url of urls) {
  14. if (typeof url !== 'string') {
  15. results.push({ url: url, error: "Invalid URL: Must be a string." });
  16. continue;
  17. }
  18. try {
  19. const result = processUrl(url);
  20. results.push({ url: url, result: result });
  21. } catch (error) {
  22. results.push({ url: url, error: error.message }); // Capture and store the error message
  23. }
  24. }
  25. return results;
  26. }

Add your comment