开发者

throwing and catching exception from function

开发者 https://www.devze.com 2023-02-09 11:29 出处:网络
function connectTo(url) { var xhr = new XMLHttpRequest(); xhr.open(\"GET\", url, false); xhr.onreadystatechange = 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?


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);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号