Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

throwing and catching exception from function

function connectTo(url) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, false);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == xhr.DONE) {
            throw "Troubles.";
        }
    };
    xhr.send();
}

try {
    connectTo("http://www.google.com");
} catch (e) {
    console.log('Exception happend.');
}

Perhaps the "catch" part will execute (in console appears the message), but the exception stays uncatched (= in console appears "Uncaught Troubles."). Why?

like image 664
Radek Simko Avatar asked Feb 06 '11 20:02

Radek Simko


1 Answers

the throw does not bubble up through a callback like that. Pass in an error handling callback and deal with it manually.

Let me illustrate your stack traces

There is no stacktrace connection between the onreadystatechange function and the connectTo function. So when you throw an error it never bubbles up to the try catch block around connectTo.

What firefox is doing is saying "Oh you did something that doesn't work. let me fix that for you and do what you think it does"

function connectTo(url, err) {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, false);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == xhr.DONE) {
            err.call(this, new Error("troubles"));
        }
    };
    xhr.send();
}

connectTo("http://www.google.com", function(e) {
     console.log(e);
});
like image 96
Raynos Avatar answered Oct 02 '22 02:10

Raynos