Ask coding questions

← Back to all posts
Detecting "broken" links
tussiez (1648)

I've been experimenting with taking random images from Imgur, and playing them as a slideshow. It works well, however I'm experiencing a bug where some links provided from the API will give a CORS error, or simply "break" or respond with 404 (I can see these in Chrome's developer console). Is there a way to detect this error? I've also thought that using an XHR request on it and detecting errors on it could fix it. Is there a correct way on doing this?
Even though the repl I'm linking on this post isn't very important, I may find this information useful for future projects.

  • Use the repl at your own risk, unrelated images may appear


The API is working fine. The API provides me a link to the image, not the image itself. This image is loaded, and this is where problems arise.


Try - catch block

Please explain your question better, but if you want errors, use a try catch block.

YodaCode (116)

@RYANTADIPARTHI -1 This does not answer the question, is very vague, and is a repeat of previous answers. It also has a bold header and is attempting to attract extra attention.


@YodaCode no, wrong. That's true, you have to use try, catch.

YodaCode (116)

@RYANTADIPARTHI Well maybe change your answer to not have a header. It makes you look stupid like you're grabbing for attention.

EDIT: And besides, they already have a try catch block.

CodeLongAndPros (1622)

@YodaCode Yes, an exception handler is the wrong answer, however, the only thing that's taboo is "pls mark as answer"

YodaCode (116)

As @Coder100 mentioned, you should move all of the code that adds the image to the DOM until after the try{} catch(err){} statement, and maybe use a loop to load a different image until it gets an actual image instead of a 404 error. Then you could set a variable, and use a finally{} statement to add the image to the DOM once you know that you have a valid image. If it doesn't make sense, I could explain it a bit more. I hope that helped!

Coder100 (18101)

@YodaCode yeah, try catch works, but I don't think it does for promises

Coder100 (18101)

I don't quite see where you are getting the request, but you could add a .catch() block.