Search code examples
node.jsphantomjscasperjs

CasperJs catch error


I don't understand how catch an error on CasperJs

I have this code

casper.thenClick('#activeCartViewForm > a');

And it return me sometimes :

[error] [remote] mouseEvent(): Couldn't find any element matching '#activeCartViewForm > a' selector 

I would like to catch it and this.die(errorMsg) to stop my casperjs.

I try to add waitForSelector :

casper.waitForSelector('#activeCartViewForm > a', function() {
    this.click('#activeCartViewForm > a');
});

But already the same problem.

And when I did :

casper.on('step.error', function(err) {
    this.die("Step has failed: " + err);
});

Nothing happens

and when I did :

casper.on('resource.error', function(err) {
    console.log(err);
    this.die("Step has failed: " + err.errorString);
});

It fund me an error never saw before and stop my phantomjs :

[error] [phantom] Error: the remote server closed the connection prematurely 

[error] [phantom] Error: The request has been aborted 

[error] [phantom] Error: The request has been aborted 

[error] [phantom] Error: the remote server closed the connection prematurely 

Thanks


Solution

  • You can catch an error in CasperJS with the statement:

    casper.on('error', function(msg, trace) {
        // process an error
    });
    

    You can try this working example:

    var casper = require('casper').create();
    
    casper.on('error', function(msg) {
        this.capture('error.png');
        this.die(msg);
    });
    
    casper.start('http://casperjs.org/', function() {
    });
    
    casper.thenClick('#activeCartViewForm > a');
    
    casper.run();