I'm building a kind of gallery app. Users are adding images by inserting URLs into the database and the HTML page is then hotlinking those. Obviously, because of link rotting, the gallery is full of images that fail to load.
I have a system to report images for various reasons, but the reports need to be sent manually by filling a form right now. I'd like to implement automatic faulty image reporting, when an image fails to load.
I already have code that detects load fail and replaces the image with a placeholder:
$("#main-img").on("error", function(event) {imgErrorHandle(event)});
function imgErrorHandle(event)
{
$("#main-img").attr("src", '/images/file-error.svg');
if (event.responseCode / 100 === 4) { reportImage("Image fails to load."); } //TODO, event.responseCode doesn't exist
}
But the problem is, that I want to send the automatic report only if the request to load the image has succeeded and simply returned an 4XX error code. I don't want to send a report, if the server just couldn't be reached, because it's likely that that's just a temporary condition.
I can't find a way to detect what kind of error triggered the onError event listener. The event object doesn't seem to contain anything useful for differentiating between the two states:
"originalEvent": {
"isTrusted": true
},
"type": "error",
"target": {
"jQuery3510050515854004395511": {
"events": {
"error": [
{
"type": "error",
"origType": "error",
"guid": 18,
"namespace": ""
}
]
}
}
},
"currentTarget": {
"jQuery3510050515854004395511": {
"events": {
"error": [
{
"type": "error",
"origType": "error",
"guid": 18,
"namespace": ""
}
]
}
}
},
"timeStamp": 3073,
"jQuery351005051585400439551": true,
"delegateTarget": {
"jQuery3510050515854004395511": {
"events": {
"error": [
{
"type": "error",
"origType": "error",
"guid": 18,
"namespace": ""
}
]
}
}
},
"handleObj": {
"type": "error",
"origType": "error",
"guid": 18,
"namespace": ""
}
}
I suppose it would be possible to load the image with AJAX and check the value of response code, but I'd like to avoid that if possible.
1 Answer 1
So first of all your error checking is bad. 4xx just means a problem at the URL you are connecting to - there are a bunch of errors that could be returned, and I think that could answer your question.
https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
So for instance, a 404 (resource not found) means that it might be available later. But a 410 (gone) means, well, gone and don't try again.
1 Comment
Explore related questions
See similar questions with these tags.
temporary condition: in a distributed world, you can't really reliably detect how temporary is the condition at the other side, is it going to be temporary for a second, minute or a week. You'd have to design a policy and then implement it, like "check every day once and if it's dead for a week, consider it dead permanently". And still, you could get false positives sometimes.