cleverpaul
cleverpaul

Reputation: 945

How can I catch a 404 error in Javascript?

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.

Upvotes: 11

Views: 25569

Answers (3)

Tamunoibi Aprekuma
Tamunoibi Aprekuma

Reputation: 217

Yes. With recent updates this is possible. You can enable it here: DevTools->Settings->General->Console->Hide network messages.

enter image description here How can I catch a 404 error in Javascript?

Upvotes: 1

cleverpaul
cleverpaul

Reputation: 945

In this case, the logging of HTTP errors in the browser console is a feature exclusive to the browser and not of Javascript, or any other website code.

This cannot be prevented.

Upvotes: 9

grantonzhuang
grantonzhuang

Reputation: 567

audio.onload = function() {
    console.log('success');
};
audio.onerror = function() {
    console.log('fail');
};
audio.src = 'http://localhost/folder/file.mp3';

Upvotes: 3

Related Questions