I'm having some trouble catching a throw from a callback in an Ajax callback. I've made a minimal test case here (code below).
In the init()
function I create a new object of class ResourceLoader
and try to get http://www.jvanderspek.com. via $.ajax. This succeeds and the ResourceLoader.prototype.onDone
function is called. Now for the sake of argument I'd like to throw an error there, and catch it at the top of my calling tree, in the init();
function, but alas, the throw is not caught. Now, this has probably to do with Ajax being executed in a different thread and the throw being called when the execution is already outside the try block, but how can I remedy it? Perhaps I'm mistaken about the cause, but then the bonus question is, why does this happen at all?
<html>
<head>
<title>testbed</title>
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
</head>
<body onload="init();">
</body>
<script type="text/javascript">
init = function() {
ResourceLoader = function(){}
ResourceLoader.prototype.load = function(){
var done = $.proxy(this.onDone, this);
$.ajax({
url: "http://www.jvanderspek.com",
}).done(done);
}
ResourceLoader.prototype.onDone = function() {
console.log( "onDone");
throw(new Error());
}
var rl = new ResourceLoader();
try {
rl.load();
}
catch(error){
window.alert( "Error caught" );
}
}
</script>
</html>