简体   繁体   中英

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.

在此处输入图片说明

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.

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.

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

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

在此处输入图片说明 How can I catch a 404 error in Javascript?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM