Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell a connect timeout error from a read timeout error in Ruby's Net::HTTP

Tags:

ruby

My question is related to How to rescue timeout issues (Ruby, Rails).

Here's the common way to rescue from a timeout:

def action
  # Post using Net::HTTP
rescue Timeout::Error => e
  # Do something
end

I'd like to determine if the exception was raised while trying to connect to the host, or if it was raised while trying to read from the host. Is this possible?

like image 937
Ben Marini Avatar asked Apr 12 '10 21:04

Ben Marini


1 Answers

Here's the solution (after Ben's fix):

require "net/http"
http = Net::HTTP.new("example.com")
http.open_timeout = 2
http.read_timeout = 3
begin
  http.start
  begin
    http.request_get("/whatever?") do |res|
      res.read_body
    end
  rescue Timeout::Error
    puts "Timeout due to reading"
  end
rescue Timeout::Error
  puts "Timeout due to connecting"
end
like image 106
Marc-André Lafortune Avatar answered Oct 11 '22 12:10

Marc-André Lafortune