Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 532
cleverpaul Avatar asked Aug 09 '17 03:08

cleverpaul


People also ask

How do I know if a website has a return 404?

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 .

How do I solve a 404 problem?

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.

How do you handle errors in JavaScript?

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.


1 Answers

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.

like image 153
cleverpaul Avatar answered Sep 23 '22 23:09

cleverpaul