Casperjs catch console.log and console.error - javascript

I'am trying to catch site console.log and console.error by casperjs. In the case of console.log I have working code:
casper.on('remote.message', function(message) {
this.echo('remote message caught: ' + message);
});
But I can't figure out how to catch console.error. I need this for catching any resources error (like images not found).

There's also the page.error handler:
casper.on("page.error", function(msg, trace) {
this.echo("Error: " + msg, "ERROR");
});
Depending on which errors you need to catch, this one may be better.

Ok it's weird to answer my own question but I found a solution on a coderwall blog posted by dpashkevich:
casper.on('resource.received', function(resource) {
var status = resource.status;
if(status >= 400) {
casper.log('Resource ' + resource.url + ' failed to load (' + status + ')', 'error');
resourceErrors.push({
url: resource.url,
status: resource.status
});
}
});
Works brilliant

You can use the following event to get remote errors:
casper.on("resource.error", function(resourceError) {
this.echo("Resource error: " + "Error code: "+resourceError.errorCode+" ErrorString: "+resourceError.errorString+" url: "+resourceError.url+" id: "+resourceError.id, "ERROR");
});
Works like charm!

Related

Ldapjs search does not appear to end

I'm new to ldapjs and ldap in general. I have the following code currently:
var search = client.search(base, opts, function(err, res) {
assert.ifError(err);
res.on('searchEntry', function(entry) {
console.log('entry: ' + JSON.stringify(entry.object));
});
res.on('searchReference', function(referral) {
console.log('referral: ' + referral.uris.join());
});
res.on('error', function(err) {
console.error('error: ' + err.message);
});
res.on('end', function(result) {
console.log('status: ' + result.status);
});
});
My search occurs correctly and finds everything needed. My issue is that it does successfully get to res.on('end') and prints out the status code (0) but the script I'm running never "officially" ends and thus causes me to have to perform a keyboard interrupt.
Additionally I tried using res.end() but was informed this was not a function. Is there something I am missing entirely? Thanks!
I think it is more nodejs question rather than ldapjs.
You can add exit your program on the 'end' event.
See:
How to exit in Node.js
Try doing this for your res.on('end'...)
res.on('end', (result => {
console.log('status: ' + result.status);
client.destroy();
});

why isn't my casperjs displaying any errors?

var casper = require('casper').create({
logLevel:'deubg',
verbose:true,
});
casper.start(someurl,function(){
not_existing_function();
})
When executing above code, all I see on the screen is debug informations that means very little to me. I am expecting to see some error saying the function being called doesn't exist, but there is not.
I thought it was just the behavior, until I see this.
The question clearly indicates he has got some error message:
ReferenceError: Can't find variable: $
Why can't I see something like this on my screen?
You're likely using PhantomJS 2.x. It has a known bug where some errors are not reported. That includes the class of errors that you're describing.
Also, registering to the various error events of CasperJS/PhantomJS doesn't help in this case, but here they are just in case:
// http://phantomjs.org/api/phantom/handler/on-error.html
phantom.onError = function(msg, trace) {
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);
};
// http://docs.casperjs.org/en/latest/events-filters.html#remote-message
casper.on("remote.message", function(msg) {
this.echo("Console: " + msg);
});
// http://docs.casperjs.org/en/latest/events-filters.html#page-error
casper.on("page.error", function(msg, trace) {
this.echo("Error: " + msg);
// maybe make it a little fancier with the code from the PhantomJS equivalent
});
// http://docs.casperjs.org/en/latest/events-filters.html#resource-error
casper.on("resource.error", function(resourceError) {
this.echo("ResourceError: " + JSON.stringify(resourceError, undefined, 4));
});
// http://docs.casperjs.org/en/latest/events-filters.html#page-initialized
casper.on("page.initialized", function(page) {
// CasperJS doesn't provide `onResourceTimeout`, so it must be set through
// the PhantomJS means. This is only possible when the page is initialized
page.onResourceTimeout = function(request) {
console.log('Response Timeout (#' + request.id + '): ' + JSON.stringify(request));
};
});
You can run something like eslint or jshint over the script to catch syntax errors and you can run your script in PhantomJS 1.9.8/1.9.7 in order to catch these sort of errors.

CasperJS/PhantomJS chokes on loading a page

I'm running the following script with phantomjs:
var casper = require('casper').create();
var url = 'https://itunesconnect.apple.com/itc/static/login?view=1&path=%2FWebObjects%2FiTunesConnect.woa%3F'
casper.on("page.error", function(msg, trace) {
this.echo("Error: " + msg, "ERROR");
this.echo("file: " + trace[0].file, "WARNING");
this.echo("line: " + trace[0].line, "WARNING");
this.echo("function: " + trace[0]["function"], "WARNING");
errors.push(msg);
});
casper.start(url, function(){
casper.wait(7000, function(){
// casper.echo(casper.getHTML());
})
})
casper.run(function() {
if (errors.length > 0) {
this.echo(errors.length + ' Javascript errors found', "WARNING");
} else {
this.echo(errors.length + ' Javascript errors found', "INFO");
}
casper.exit();
});
Until a few days ago I could access the page which loads an iframe that contains 2 form fields, to allow user login.
Now I get the following error:
Error: Error: undefined is not a constructor (evaluating '$stateParams.path.startsWith('/')')
at setupDSiFrame (https://itunesconnect.apple.com/itc/static-resources/controllers/login_cntrl.js?cache=111920151100:99:46)
at https://itunesconnect.apple.com/itc/static-resources/controllers/login_cntrl.js?cache=111920151100:19:37
at $digest (https://itunesconnect.apple.com/itc/js/compiled/lib/vendor.js?cache=111920151100:13:11750)
at $apply (https://itunesconnect.apple.com/itc/js/compiled/lib/vendor.js?cache=111920151100:13:13237)
at f (https://itunesconnect.apple.com/itc/js/compiled/lib/vendor.js?cache=111920151100:12:56414)
at r (https://itunesconnect.apple.com/itc/js/compiled/lib/vendor.js?cache=111920151100:12:65848)
at onreadystatechange (https://itunesconnect.apple.com/itc/js/compiled/lib/vendor.js?cache=111920151100:12:66409)
file: https://itunesconnect.apple.com/itc/js/compiled/lib/vendor.js?cache=111920151100
line: 12
The page loads fine using slimerjs as the engine, but when using slimerjs the login form does not get filled in because the window is not in focus.
I believe this is an issue where casper is using an old version of WebKit and chokes on loading the page. How would I fix this?
Too late to solve the problem but maybe useful for future reference if somebody finds the question searching for a problem with startsWith in PhantomJS (as I did): startsWith method was added on the ECMAScript 6 specification, which is not supported by PhantomJS.
A good polyfill for this is mathiasbynens/String.prototype.startsWith

Phantomjs does not open web page

I have started testing campus2020 site with casperjs (1.1.0-beta3) + phantomjs (1.9.8). And faced with the problem that site is not opening but instead tests just freeze. I have taken script example from phantomjs site:
var page = require('webpage').create();
page.open('http://informatik.uni-leipzig.de/campus2020', function(status) {
console.log("Status: " + status);
if(status === "success") {
page.render('example.png');
}
phantom.exit();
});
It worked fine on other sites. I have tested opening the campus2020 site with phantomjs on several environments: win 7, Ubuntu 14.04, with ghostdriver and java selenium webdriver, with phantomjs which is run in selenium grid on RHEL 6.6. All this options failed. I have tried to add userAgent option and setTimeout. Nothing changed. Also I tried to open this site using testing framework based on selenium webdriver which used phantomjs but it worked in the same way - phantomjs initialized and then freezes. Any ideas how could be this issue solved?
Update
Now my code looks like these:
var page = require('webpage').create();
console.log("Page is going to be opened...")
page.open('http://informatik.uni-leipzig.de/campus2020/', function(status) {
console.log("Status: " + status);
if(status === "success") {
page.render('example.png');
}
phantom.exit();
});
page.onConsoleMessage = function(msg, lineNum, sourceId) {
console.log('CONSOLE: ' + msg + ' (from line #' + lineNum + ' in "' + sourceId + '")');
};
page.onError = function (msg, trace) {
console.log(msg);
trace.forEach(function(item) {
console.log(' ', item.file, ':', item.line);
})
}
page.onResourceError = function(resourceError) {
console.log('Unable to load resource (#' + resourceError.id + 'URL:' + resourceError.url + ')');
console.log('Error code: ' + resourceError.errorCode + '. Description: ' + resourceError.errorString);
};
page.onResourceTimeout = function(request) {
console.log('Response (#' + request.id + '): ' + JSON.stringify(request));
};
And no errors are shown.
I don't know why there is this issue, but you can update to PhantomJS 2 and it will work. There are not yet binaries for Linux, so you will need to build it yourself.
You will also need to update your CasperJS version, because the 1.1-beta3 doesn't support PhantomJS 2, but the master branch on GitHub does.
phantomjs --debug=true phantom_test.js

Catch script error - type,line and file

window.onerror = function(type, file, line){
if(type) {
console.log(type);
}
if(file) {
console.log(file);
}
if(line) {
console.log(line);
}
}
this code returns "Script error" when there is an error at some of the .js files. I need the type, file and line of the error. How can I get it?
When window throws error this script works perfect but it is not the same when there is error in the .js file.
I know that these things I can find on the console but imagine that I don't have one and i cannot install.
window.onerror = ErrorLog;
function ErrorLog (msg, url, line) {
console.log("error: " + msg + "\n" + "file: " + url + "\n" + "line: " + line);
return true; // avoid to display an error message in the browser
}
The post of Cryptic "Script Error." reported in Javascript in Chrome and Firefox should answer your "Script Error." problem. Namely it is probably caused by "Same origin policy".
Though I am still looking for why webkit will give me "undefined" file name and "0" line number for uncaught exception.
Here's what I use to capture errors. I have it request an image whose url points to a server side script.
function logJSErrors(errObj) {
if (!errObj || !errObj.lineNumber || errObj.lineNumber == 0) {
return; // can't use it any way.
}
if (window.location && window.location.toString().indexOf('rfhelper32.js') >= 0) {
return; // ignore the stupid Norton/Firefox conflict
}
var img = new Image();
img.src = "/jserror?m=" + encodeURIComponent(errObj.message) +
"&location=" + encodeURIComponent(window.location) +
"&ln=" + encodeURIComponent(errObj.lineNumber) +
"&url=" + encodeURIComponent(errObj.fileName) +
"&browser=" + encodeURIComponent(errObj.browserInfo);
}
window.onerror = function (msg, url, line) {
logJSErrors({ message : msg,
lineNumber : line,
fileName : url,
browserInfo : window.navigator.userAgent
});
// if a jquery ajax call was running, be sure to make the spinning icons go away
if (jQuery) {
try {
jQuery.event.trigger("ajaxStop");
} catch(e) {/* do nothing */
}
}
};

Categories

Resources