Javascript Runtime Exception

1

I'm trying to make a dynamic file call where I have a input that gets a name and a file with that name is loaded in the <source> in js, when the person types a file name that does not exist in the folder you would need to display an error message and not run play() , but for some reason in the code below the catch does not catch the error. I thought of doing a check if the file exists before assigning the name, but I'd like a simple solution without needing API or anything like that and have not found it. In the end I need a way or to handle the error GET net::ERR_FILE_NOT_FOUND or to verify in a simple way, without needing API, if the file exists before assigning (if possible, of course).

Follow the Code:

function play (element) {
    try {
        audioElement[played] = document.createElement('audio');

        audioElement[played].innerHTML = '<source src="../_songs/' + element.parentNode.getElementsByClassName("musica-location")[0].value + '.mp3"'+ ' type="audio/mpeg" />';
        audioElement[played].play();
    } catch (err) {
        alert("Erro, arquivo não encontrado", err);
    }


    element.setAttribute("data-audio", played++);
}
    
asked by anonymous 30.11.2016 / 05:11

1 answer

1

The error ERR_FILE_NOT_FOUND , in fact, is not a JS error, but rather an error that the browser plays so that you can debug your code more easily, for this reason you will never be able to get it with the catch in code.

As I already described some answers below as:

Some options are available, among them the parallel reading of the file via AJAX with jQuery more or less this way:

$.get("/caminho/do/arquivo", function(data, status) {  
   console.log("Status do arquivo: "+status); 
   //...resto do seu código...
});

Another option is to try to use the built-in error function in the HTML of the <audio> tag as <audio onerror=...> as this link:

You can either use a pre-existing function as <audio onerror='suafuncao'> or use JS itself to create a listener for this event in your element:

object.onerror = function(){
  //...
};
    
30.11.2016 / 11:07