How would I do a while statement with net/http if it keeps timing out?

StackOverflow https://stackoverflow.com/questions/8320315

  •  25-10-2019
  •  | 
  •  

سؤال

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?

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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

require 'open-uri'
sleep 10 until response = open(url).read rescue nil
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top