Javascript Runtime Exception

Asked

Viewed 138 times

1

I’m trying to make a dynamic file call where I have one input that receives a name and is loaded a file with this name in the <source> in js, when the person enters a file name that does not exist in the folder would need to display an error message and not execute the play(), but for some reason in the code below the catch doesn’t catch the error. I thought of doing a check if the file exists before assigning the name, but I would like a simple solution without needing API or anything like that and did not find. In the end I need a way or treat the mistake GET net::ERR_FILE_NOT_FOUND or to check in a simple way, without needing API, whether the file exists before assigning (if possible, of course).

Follows 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++);
}
  • I believe the best way is to check if the file exists, because the Trycatch which is doing is not giving error in the execution of the code but rather file error not found, which would not fall in the catch.

1 answer

1


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

As 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 using the error function you are using built-in in the HTML tag <audio> as <audio onerror=...>according to this link:

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

object.onerror = function(){
  //...
};

Browser other questions tagged

You are not signed in. Login or sign up in order to post.