I cannot figure out how to catch an exception from a function that gets called from image.onload
. Notice the following example:
function afterImgLoads() {
throw 'This is being thrown from img.onload!';
}
try {
var img = new Image();
img.onload = afterImgLoads;
img.src = 'path/to/valid/image.jpg';
} catch(e) {
throw 'This is being thrown after setting img.src';
}
In the above example, I cannot figure out how to get the second throw statement to be thrown when afterImgLoads()
throws its own error.
I cannot figure out how to catch an exception from a function that gets called from image.onload
. Notice the following example:
function afterImgLoads() {
throw 'This is being thrown from img.onload!';
}
try {
var img = new Image();
img.onload = afterImgLoads;
img.src = 'path/to/valid/image.jpg';
} catch(e) {
throw 'This is being thrown after setting img.src';
}
In the above example, I cannot figure out how to get the second throw statement to be thrown when afterImgLoads()
throws its own error.
4 Answers
Reset to default 6You maybe able to use onerror
img.onerror = onErrorFunction;
It will call that function in the event of an error loading the image
You can set window.onerror which will be called on an otherwise uncaught exception anywhere on your page.
You can try catching the error from the onLoad
function
function afterImgLoads() {
throw 'This is being thrown from img.onload!';
}
let img = new Image();
img.onload = () => {
try {
afterImgLoads();
} catch (e) {
console.warn(e);
}
}
img.src = "https://www.shutterstock./image-vector/bear-monochrome-image-head-on-260nw-579987739.jpg";
It is impossible for that catch to throw statement since the onload happens asynchronously.