Reputation: 23959
If I have multiple fetch()
calls within a Promise.all
block, when one fails, it all fails. That's cool, I need them all to resolve.
However, how can I find which one actually failed?
In the following code, the catch error
tells me:
TypeError: Failed to fetch`
which makes it impossible to construct an effective user error message should I choose to do so.
const goodUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
const badUrl = 'https://ajax.googleapis77.com/ajax/libs/jquery/2.1.3/jquery.min.js';
Promise.all([
fetch(goodUrl),
fetch(badUrl), /* will fail */
fetch(goodUrl)
]).then(([response1, response2, response3]) => {
console.log(response1);
console.log(response2);
console.log(response3);
}).catch((err) => {
console.log(err);
});
Here's a fiddle (a snippet didn't play nice)
I have looked for duplicates, this is not one as the examples throw the same error
Upvotes: 2
Views: 5111
Reputation: 707158
I'd suggest you make your own little wrapper around fetch()
that throws a custom error that contains the desired information:
function myFetch(url) {
return fetch(url).catch(function(err) {
let myError = new Error("Fetch operation failed on " + url);
myError.url = url;
throw myError;
});
}
const goodUrl = 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js';
const badUrl = 'https://ajax.googleapis77.com/ajax/libs/jquery/2.1.3/jquery.min.js';
Promise.all([
myFetch(goodUrl),
myFetch(badUrl), /* will fail */
myFetch(goodUrl)
]).then(([response1, response2, response3]) => {
console.log(response1);
console.log(response2);
console.log(response3);
}).catch((err) => {
console.log(err);
});
Working jsFiddle demo: https://jsfiddle.net/jfriend00/1q34ah0g/
Upvotes: 2
Reputation: 3940
You could just catch each of them individually and throw
some custom errors like:
...
Promise.all([
fetch(goodUrl).catch(err => {
throw {url: goodUrl, err};
}),
fetch(badUrl).catch(err => {
throw {url: badUrl, err};
}),
fetch(goodUrl).catch(err => {
throw {url: goodUrl, err};
})
])
...
Upvotes: 6