I am attempting to load multiple text files using fetch requests with Promise.all. Here is my implementation:
////////////////////////////////////////
const loadTextFiles = (allUrls, textUrls) => {
const requests = textUrls.map(url => fetch(url));
return Promise.all(requests)
.then(responses => Promise.all(
responses.map(response => response.text())
))
.then(texts => texts.forEach(
(text, i) => allUrls[textUrls[i]] = text
))
.catch(err => {
// log("HERE");
throw exception("networkLoader",
"loadTextFiles",
`error in loadTextFiles: ${err.toString()}`);
});
};
The arrays allUrls
and textUrls
contain the URLs of all resources (files with any extension) and text resources (files with .txt extension) respectively. The textUrls
array is constructed from the allUrls
array. After fetching the data, it is stored inside the allUrls
array. For example, if
allUrls = [ "image.png", "essay.txt" ]
, then textUrls = [ "essay.txt" ]
. When calling the loadTextFiles
function:
await loadTextFiles(allUrls, textUrls);
You can access the contents of "essay.txt" by accessing allUrls["essay.txt"]
. Everything works well as long as all text files exist and can be retrieved.
The issue arises when there are problems in retrieving the files. Even though I have a catch
block to handle errors in Promise.all, it does not seem to work. For instance, when requesting a file that does not exist like fileThatDoesNotExist.txt, I receive a 404 (Not Found) error in the browser console but the code inside the catch block does not execute. I have even tested it with a custom log
function, which also does not run. How can I catch the error and re-throw it?
Edit: To clarify, when mentioning catching the error, I mean detecting the 404 error and throwing an exception (such as a custom exception
object).