简体   繁体   English

如何在 Javascript 中捕获 404 错误?

[英]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.我有一个 HTML 音频元素,我正在将该元素的“src”属性动态设置为存储在我们局域网上的音频文件。

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.有时,我指向的源音频文件的链接已损坏,这会导致生成 404 错误并将其记录到浏览器控制台。

在此处输入图片说明

I want to be able to catch the 404 errors so as to prevent them being logged to the console.我希望能够捕获 404 错误,以防止它们被记录到控制台。

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.不幸的是,我的 try/catch 语句完全没有做任何事情,错误仍然记录到控制台。 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).由于我的应用程序的性质,会有很多 404 错误,这是正常的和预期的,但对用户来说它看起来非常不稳定和“丑陋”(如果他们碰巧打开控制台)。

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.在这种情况下,在浏览器控制台中记录 HTTP 错误是浏览器独有的功能,而不是 Javascript 或任何其他网站代码。

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.您可以在此处启用它:DevTools->Settings->General->Console->Hide network messages。

在此处输入图片说明 How can I catch a 404 error in Javascript?如何在 Javascript 中捕获 404 错误?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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