如何使casperjs继续而不是退出异常?

时间:2015-03-20 02:06:34

标签: javascript casperjs

当我使用CasperJS处理网页时,我发现了一个奇怪的案例。即使我使用try-catch块,程序也会在异常时退出! 我的代码如下。我希望程序可以继续运行下一个循环。但是,当找不到iframe时,会抛出类似CasperError: Frame number "1" is out of bounds.的异常并退出整个程序。 catch块中的myStore函数也不会运行。

有人可以帮助我们吗?

try {
    // find the iframe and then fill in the message
    casper.withFrame(1, function() {
        casper.evaluate(function(message) {
            // some function code
        });
        casper.wait(1000, function() {
            myStore(stores, index+1);  
            // when the iframe not found, function myStroe will not be run
        });
    });
} catch (err) {
    output(false, "error=" + err.message);
    myStore(stores, index+1);  // myStroe will not be run on Exception
}

我尝试了Artjom B给出的例子,但它不起作用。

var frameExists = false;
casper.withFrame(1, function() {
    frameExists = true;
    casper.evaluate(function(message) {
        // some function code
    });
});
casper.wait(3000, function() {
    if (frameExists) {
        // the program run this branch and got stuck in the nonexistent selector since the frame is not found.
        casper.click("input#send");  
        // some function code
        output(true, "index=" + index + ";storeId=" + store.id + ";succeeded");
        myStore(stores, index+1);
    } else {
        output(false, "index=" + index + ";storeId=" + store.id + ";error=" + err.message);
        myStore(stores, index+1);
    }
});

很奇怪。我不知道为什么程序会使用frameExists === true进入错误的分支。

1 个答案:

答案 0 :(得分:1)

有一个名为exitOnError的便捷小选项:

一开始:

var casper = require('casper').create({
    exitOnError: false
});

或更晚:

casper.options.exitOnError = false;

如果您希望myStore()无论框架是否存在都可以运行,您可以执行以下操作:

casper.then(function(){
    var frameExists = false;
    // find the iframe and then fill in the message
    casper.withFrame(1, function() {
        frameExists = true;
        casper.evaluate(function(message) {
            // some function code
        });
        casper.wait(1000, function() {
            myStore(stores, index+1);  
            // when the iframe not found, function myStroe will not be run
        });
    });
    casper.then(function(){
        if (!frameExists) {
            output(false, "error=" + err.message);
            myStore(stores, index+1);  // myStroe will not be run on Exception
        }
    });
});