Search code examples
javascriptimageloadcontent-typeresponse.contenttype

Javascript image load: get error status


I am loading a image trough javascript:

myimage.src = "/mycontroller/mymethod";
myimage.alt = "image";
myimage.onload = function(){
    $('body').append(myimage);
};    

But, somethimes my controller method should return an error, with the http status 500. So, the content-type will not be image/png anymore. Will be text.
There's a way to identify this error when loading the image, get the error message and display an alert?


Solution

  • If the method is not guaranteed to succeed, a better solution would be for your method to return Javascript code which either loads an image, or displays an error. As far as I know, there is no way to tell if a URL to an image is actually an image, or if it's text data. I would love it if someone else provides an answer that proves me wrong!