最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to catch an exception from image onload - Stack Overflow

programmeradmin4浏览0评论

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.

Share Improve this question edited Nov 20, 2012 at 17:51 fronzee asked Nov 20, 2012 at 0:57 fronzeefronzee 1,8282 gold badges24 silver badges36 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

You 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.

发布评论

评论列表(0)

  1. 暂无评论