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.
If you have ever wanted to check whether a page has returned a 404 for any reason, one of the easiest ways is to use this little helper function UrlExists() with the current url, given by window. location. href. This will return a true if the http status is anything except a 404, otherwise it will return false .
404 error messages may occur when internet users come from external links from other sites that redirect them to deleted web pages. To solve this issue, restore the site backup. Note that this method only works if certain website pages are broken or show a 404 error.
JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally block, similar to other languages like Java or C#. try: wrap suspicious code that may throw an error in try block. catch: write code to do something in catch block when an error occurs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With