Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch js errors when adding a script dynamically

Why I cannot handle js errors when adding a javascript code dynamically?

Here is the code:

try {
  var element = document.createElement("script");
  element.language = "javascript";
  element.type = "text/javascript";       
  element.defer = true;
  element.text = "this is not a javascript code";
  var head = document.getElementsByTagName('head')[0];
  head.appendChild(element);
} catch(err) {
  alert("error caught");
}

The error caught alert isn't shown even if the script is incorrect.

like image 734
starikovs Avatar asked Dec 30 '13 10:12

starikovs


1 Answers

As far as I know, there's no way to handle errors (even syntax ones) on certain script tag. You could use window.onerror and look for SyntaxError at the beginning of the error message. I suppose, this is the kind of errors, you're trying to catch.

like image 103
kirilloid Avatar answered Oct 24 '22 02:10

kirilloid