I'm writing an application in JavaScript that should create a new image. Sometimes it fails. I was able to detect the times when it does by attaching an image.onerror
event listener. Question is: How may I learn what error occured - what parameters does the error object for images bring? So far I only found out that
image.onerror = function (errorMsg, url, lineNumber, column, errorObj) {
console.log('Error: ' + errorMsg + ' Script: ' + url + ' Line: ' + lineNumber
+ ' Column: ' + column + ' StackTrace: ' + errorObj);
}
which I got from: javascript: how to display script errors in a popup alert?
returns Error: [object Event] Script: undefined Line: undefined Column: undefined StackTrace: undefined
and in the error object I couldn't find anything related to message or error code.
What is onerror() Method in JavaScript? The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is fired on the window object whenever an exception occurs on the page.
The Error object and error. It contains 3 standardized properties: message, fileName, and lineNumber. Redundant values that already provided to you via window. onerror .
Definition and Usage The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image). Tip: When used on audio/video media, related events that occurs when there is some kind of disturbance to the media loading process, are: onabort.
onerror = function() { alert("Error occurred while loading image"); }; There are some notes though: Most resources start loading when they are added to the document.
AFAIK the image.onerror handler will receive a single Event parameter that doesn't contain any info on the cause of the error.
If you want to trap errors on a normal HTML img
element (rather than dynamically creating one via the DOM), this seems to work well:
<img src="http://yourdomain/site/badimage.png"
onerror="javascript:imageErrorHandler.call(this, event);"/>
Note that the .call(this, event)
syntax is important so you have access to the this
and event
objects in your error handler.
Then you can define an image error handler like the following. (Make sure it is defined before the img
element to avoid race conditions.) Assuming you have jQuery wired up:
function imageErrorHandler(evt) {
var $e = $(this);
var src = $e.attr("src");
console.log("Image URL '" + src + "' is invalid.");
};
Tested this in Chrome. Have not tried other browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With