How can I catch a 404 error in Javascript?

Viewed 18368

I have an HTML audio element and I am dynamically setting the "src" property of the element to an audio file stored on our local area network.

This is how it works:

function setSource(source) {
   audio.src = source;
}

var audio = new Audio();
var source = "http://localhost/folder/file.mp3";
setSource(source);

Sometimes, the source audio file that I am pointing to has a broken link and this causes a 404 error to be generated and logged to the browser console.

enter image description here

I want to be able to catch the 404 errors so as to prevent them being logged to the console.

This is how I attempted it:

function setSource(source) {
  try {
    audio.src = src;
  }//end try
  catch (e) {
    //do nothing
  }//end catch
}//end setSource

var audio = new Audio();
var source = "http://localhost/folder/file.mp3";
setSource(source);

Unfortunately, my try/catch statement does absolutely nothing and the error is still logged to the console. Am I doing something wrong?

Due to the nature of my app, there will be lots of 404 errors, which is normal and expected, but it looks really unstable and "ugly" to the users (if they happen to open the console).

FYI: I am using Google Chrome.

3 Answers
Related