So take a look at the below rough code:
function Manager()
{
try
{
A();
}
catch(e)
{
//......Never caught...
}
}
function AjaxCallback()
{
try
{
B();
}
catch(e)
{
throw e;
}
}
function B()
{
throw {//something here}
}
I am able to catch the exception in my callback function when thrown from B fine. However, when I rethrow that same error in the callback, it’s never caught in the manager. Why? Regardless of the fact that the callback can execute whenever, it’s chain here still seems to dictate that the error should bubble back up and caught by manager although as stated, this does not happen. Can anyone explain to me why this is and maybe how to fix this?
The callback is invoked asynchronously. There’s “nobody home” listening for exceptions when the callback is called. The browser invokes the callback in response to the asynchronous event of the HTTP request completing. Your
try ... catchblock is a static construct, and as such it won’t play any role in the handling of exceptions thrown by your callback function. Thetry ... catchis executed synchronously, and it’s a thing of the past by the time the callback function happens. Thus, you can’t catch an exception that way; it just doesn’t make any sense.What you can do instead is to set up your Ajax stuff such that when you decide it’s time to contact the server, you provide the code necessary to make the request and the code you want to run when the request is successful, and the code to run when the request fails. Exactly how you do that depends on the Ajax mechanism you’re using.