How to handle image errors in Angular

Hi,
I’ve read the great article Best practices for Error handling in Angular
I’m wondering if there is there a similar way to detect images that fail to load because Angular is not detecting them in ErrorHandler.

image

I’m familiar with binding to error event directly on the <img> tag but I’m looking for global solution like ErrorHandler.

Angular doesn’t catch it probably because the image request is not initialized by Angular. For global event handling, check GlobalEventHandlers.onerror:

When a resource (such as an <img> or <script> ) fails to load , an error event using interface Event is fired at the element that initiated the load, and the onerror() handler on the element is invoked. These error events do not bubble up to window, but (at least in Firefox) can be handled with a window.addEventListener configured with useCapture set to True.

2 Likes

Hi Maxim, thank you for your response.

I’m looking into window.addEventListener() and it’s working with capture: true.
Could you just explain what you mean by:

image request is not initialized by Angular

I have this image in child component. I’m trying to detect third party images error but the same issue is with inline images

<div class=""><img src="random.svg"></div>

And I get this error in browser console but nothing is detected by ErrorHandler

Well, it seems that although the element is being created by Angular, it simply creates an element and doesn’t attach an error handler to native DOM element:

if it did attach the handler, the browser would trigger it and then Angular could notify ErrorHandler:

but it doesn’t do that.

1 Like