How to handle unresolved promise rejection
Closed this issue · 2 comments
Hi Vivaxy,
First of all, thanks for your simple yet great component!
I've encountered an issue when trying lo load remote images that are not actually images (Because they've been removed for example). When this happens I'm getting the following:
YellowBox.js:71 Possible Unhandled Promise Rejection (id: 64):
Error: Unexpected HTTP code Response{protocol=h2, code=403, message=, url=some URL that doesn't return an Image}
Error: Unexpected HTTP code Response{protocol=h2, code=403, message=, url=some URL that doesn't return an Image}
at createErrorFromErrorData (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:4551:15)
at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:4509:25
at MessageQueue.__invokeCallback (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:4830:16)
at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:4676:16
at MessageQueue.__guard (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:4765:9)
at MessageQueue.invokeCallbackAndReturnFlushedQueue (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:4675:12)
at t (file:///Applications/React%20Native%20Debugger.app/Contents/Resources/app.asar/js/RNDebuggerWorker.js:1:18504)
That's fine because I have an onError handler on the component that creates the AutoHeightImage component and I'm taking appropriate actions.
However, I realized that the Warning was being generated by the following function in your code:
const getImageSizeMaybeFromCache = async(imageURL) => {
let size = getImageSizeFromCache(imageURL);
if (!size) {
size = await loadImageSize(imageURL);
cache.set(imageURL, size);
}
return size;
};
I kind of fixed this with the following change (quick and dirty solution):
const getImageSizeMaybeFromCache = async(imageURL) => {
let size = getImageSizeFromCache(imageURL);
if (!size) {
try {
size = await loadImageSize(imageURL);
} catch (error) {
size = 0 //This should probably be handled better
}
finally {
cache.set(imageURL, size);
}
}
return size;
};
At least with this I managed to remove the Yellow Warning.
I hope it helps you. And let me know if you have any suggestions.
Thanks again!!
Thanks for your suggestion. If an imageURL is not correct, errors will be rejected twice.
Maybe not rejecting it in the first place is a better choice.
const loadImageSize = (imageURL) => {
return new Promise((resolve, reject) => {
Image.getSize(imageURL, (width, height) => {
// success
resolve({ width, height });
}, (err) => {
// error
reject(err);
});
});
};