Ben Marini Ben Marini - 4 months ago 25
Ruby Question

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

My question is related to http://stackoverflow.com/questions/2370140/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?

Answer

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