Search code examples
javascriptimageexceptiontry-catch

How to catch an exception from image onload


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.


Solution

  • It is impossible for that catch to throw statement since the onload happens asynchronously.