Jonathan.Brink Jonathan.Brink - 3 months ago 21
Javascript Question

PhantomJS error handling

I'm having a hard time understanding how PhantomJS handles errors.

I have a locally installed Apache server running (xampp), and when I manually visit "http://localhost/" I get the "It Works!" page.

As a test, I wrote a small file (called forceError.js) that purposely causes an unchecked exception:

var page = require('webpage').create(),
url = 'http://localhost/';

page.onError = function(msg, trace) {
console.log("page.onError");
var msgStack = ['ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function +'")' : ''));
});
}
console.error(msgStack.join('\n'));
};

phantom.onError = function(msg, trace) {
console.log("phantom.onError");
var msgStack = ['PHANTOM ERROR: ' + msg];
if (trace && trace.length) {
msgStack.push('TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + (t.file || t.sourceURL) + ': ' + t.line + (t.function ? ' (in function ' + t.function +')' : ''));
});
}
console.error(msgStack.join('\n'));
phantom.exit(1);
};

page.open(url, function (status) {
console.log("status: " + status);

// an undefined function
thisShouldForceAnError();
});


When I run this using:

phantomjs.exe forceError.js


First I get "status: success" and then the process just hangs. I don't see either page.onError or phantom.onError being invoked.

Is there some property or something I need to turn on to get general error handling?

I'm on Windows 7, PhantomJS version 2.0.0, and running this in my "git bash" shell.

Answer

Tested on MacOS and experienced exactly the same behaviour, which indeed is a bit unintuitive and most likely just a bug. The weird thing is that, if you call an undefined function from the top most scope phantom.onError is invoked correctly1.

As a workaround you can just wrap body of the open callback with a try/catch. Hopefully it will do the job.

Just to clarify: page.onError is invoked if an error occurred while executing code of the requested page - not the phantom script itself. I have been relying on page.onError for a while now and it seems to work pretty stable. (Although some errors only occur in phantomjs engine, but not in regular browsers.)


1 Actually: "phantom.onError" gets printed on the console infinitely as console.error is not supported by phantomjs.