I’ve been writing a script to monitor our production app that has been playing up a lot lately. The problem is that the service on the server continues to run but when trying to access the main page it just sits there loading indefinitely.
The idea is to write a Watir script that brings up the main page every minute and notifies us if it displays an error, or, as has been happening, sits there loading indefinitely.
One of the things I love about Watir is how it handles browser synchronization: it’s really neat. To quote Bret’s design objective:
“Watir is deterministic. Watir does not wait X seconds. It waits until the page is loaded. Period.”
- Bret Pettichord
So this is great when you’re writing a test script, but as my page sometimes loads indefinitely, so does my Watir script:
require 'watir' check_url = 'www.google.com' ie = Watir::IE.new() ie.goto(check_url) puts ie.check_for_http_error()
I did some research and found a ruby Timeout class that I figured I could use. My first attempt was to do something like this:
require 'watir' check_url = 'www.google.com' ie = Watir::IE.new() begin</pre> Timeout::timeout(30) do ie.goto(check_url) puts ie.check_for_http_error() end rescue puts 'timed out' end
This seemed to work when the page didn’t timeout, but for some reason it wasn’t catching the timeout. So I did a bit of digging and found out a rescue clause in ruby with no following class only catches exceptions of type StandardError, a subclass of Exception. So it wasn’t catching the Timeout::Error exception. The way to catch this exception is to always include the Exception clause, and to pass it to a variable such as ‘e’.
The final script looked something like:
require 'watir' check_url = 'www.google.com' ie = Watir::IE.new() begin Timeout::timeout(30) do ie.goto(check_url) puts ie.check_for_http_error() end rescue Exception => e puts 'timed out: '+e end
In my research on Timeout::timeout I found this article that explains how it’s actually dangerous to use Timeout::timeout, but until I figure out a better solution it seems to work pretty well for me.