turbod
turbod

Reputation: 1988

How can I handle Connection timed out error in ruby Net/HTTP?

I try this code, but when the proxy is too slow I get connection timed out error. How can I solve this? I tried Exception handling but doesn't work. Can anybody help?

 Net::HTTP.new('example.com', nil, '140.113.182.81', '808').start { |http|  

      begin   
        response = http.request  
        p response  
      rescue Timeout::Error  
        p 'timed out'   
      end  
    }  

Upvotes: 2

Views: 1800

Answers (1)

Simone Carletti
Simone Carletti

Reputation: 176402

The Timeout::Error is raised by the Net::HTTP.connect method that is executed by start, not by request.

It means that in order to rescue the timeout, the whole Net::HTTP call should be inside the begin block.

  begin   
    Net::HTTP.new('example.com', nil, '140.113.182.81', '808').start do |http|  
      response = http.request  
      p response  
    end
  rescue Timeout::Error  
    p 'timed out'   
  end  

Upvotes: 1

Related Questions