tetutato
tetutato

Reputation: 648

Catch errors caused by evaluate() in CasperJS / PhantomJS?

I'm wondering why the following code isn't picking up errors output in the console by javascript code executed using the evaluate() method.

casper.on 'resource.error', ->
    @echo 'Resource error: ' + "Error code: "+resourceError.errorCode+" ErrorString: "+resourceError.errorString+" url: "+resourceError.url+" id: "+resourceError.id, "ERROR"

Since evaluate() executes the code in the context of the web browser, shouldn't any errors caused by it be caught by the code above?

Upvotes: 1

Views: 1737

Answers (1)

Artjom B.
Artjom B.

Reputation: 61892

The documentation to 'resource.error' says it all:

Emitted when any requested resource fails to load properly. The received resourceError object has the following properties

It has nothing to do with the page errors. In fact casper.evaluate() and the PhantomJS equivalent page.evaluate() don't send requests to the page in order to interact with it. It is all baked into the same engine. The only limitation is that evaluate() is sandboxed. It doesn't have access to variables defined outside, so you have to explicitly pass them in and out.

What you want is the "page.error" event:

Emitted when retrieved page leaves a Javascript error uncaught


Take for example the following complete script:

var casper = require('casper').create();

casper.on("remote.message", function(msg) {
    this.echo("Console: " + msg);
});

casper.on("page.error", function(msg, trace) {
    this.echo("Error: " + msg);
});

casper.on("resource.error", function(msg, trace) {
    this.echo("Res.Error: " + msg);
});

casper.start("http://example.com",function(){
    this.evaluate(function(){
        null.pop();
    });
});

casper.run();

It outputs:

Error: TypeError: null is not an object (evaluating 'null.pop')

Upvotes: 4

Related Questions