Question

I have the following code:

require 'rubygems'
require 'net/http'
require 'uri'
url = URI.parse('http://servername.tld/up.txt')
response = Net::HTTP.get_response(url)

@yes = response.body
until @yes == "yes"
  puts "It's down"
end

The contents of /up.txt is

yes

However, it keeps timing out when it (that is, the server hosting up.txt) is down, with this:

/home/jrg/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/net/http.rb:644:in `initialize': Connection refused - connect(2) (Errno::ECONNREFUSED)

Related, but didn't help: Why do I get "Errno::ECONNREFUSED" with 'net/http' in Rails?

Do I need to consider using something other than Net::HTTP?

Was it helpful?

Solution

Just put the part that's throwing the exception in a rescue block.

def up?(url)
  begin
    Net::HTTP.get_response(url).body == "yes"
  rescue Errno::ECONNREFUSED
    false
  end
end

until up?(url)
  puts "It's down"
end

OTHER TIPS

You might like open-uri, it's much tidier:

require 'open-uri'
sleep 10 until response = open(url).read rescue nil
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top