如何使casperjs继续而不是在出现异常时退出

How to make casperjs continue instead of exit on exception?

本文关键字:异常 退出 casperjs 何使 继续      更新时间:2023-09-26

当我使用CasperJS处理web时,我发现了一个奇怪的情况。即使我使用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错误的分支。

有一个方便的小选项,叫做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
        }
    });
});