Catch js errors when adding a script dynamically
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.
the catch statement should be at different level of code try to catch the error inside your added code also the error should be exception not syntax error
<html>
<head>
<script type="text/javascript">
try {
var element = document.createElement("script");
element.language = "javascript";
element.type = "text/javascript";
element.defer = true;
element.text = "try{callingAnonymousMethod();} catch(ex) {alert('error caught');}";
var head = document.getElementsByTagName('head')[0];
head.appendChild(element);
} catch(err) {
alert("error caught");
}
</script></head>
<body>
</body>
<html>