I need to rescue a Timeout::Error
raised from a the Redis library but i'm running into a problem, rescuing that specific class doesn't seem to work.
begin
Redis.new( { :host => "127.0.0.X" } )
rescue Timeout::Error => ex
end
=> Timeout::Error: Timeout::Error from /Users/me/.rvm/gems/ree-1.8.7-2011.03@gowalla/gems/redis-2.2.0/lib/redis/connection/hiredis.rb:23:in `connect'
When i try to rescue Exception
it still doesn't work
begin
Redis.new( { :host => "127.0.0.X" } )
rescue Exception => ex
end
=> Timeout::Error: Timeout::Error from /Users/me/.rvm/gems/ree-1.8.7-2011.03@gowalla/gems/redis-2.2.0/lib/redis/connection/hiredis.rb:23:in `connect'
If i try to raise the exception manually, i can rescue it but don't know why i can't rescue it when it's called from within the Redis Gem (2.2.0).
begin
raise Timeout::Error
rescue Timeout::Error => ex
puts ex
end
Timeout::Error
=> nil
Any clue how to rescue this exception?
You ran this code in irb, right? The exception you are getting is not actually being raised by
Redis.new
. It is being raised by theinspect
method, which irb calls to show you the value of the expression you just typed.Just look at the stack trace (I shortened the paths to make it legible):
As you can see above, the exception occurs inside
inspect
, notRedis.new
. When you callinspect
on a Redis object, instead of just printing out its state it actually does a lot of things. In this case,inspect
attempts to connect to the server and throws an exception when that times out. This seems like a very bad design to me and maybe we should file a bug report to the maintainers of the Redis gem.This leads to some interesting behavior in IRB:
Redis.new(:host => "google.com")
results in an exception as shown aboveRedis.new(:host => "google.com"); 'hello'
results in '=> "hello"
'If you want to catch this exception, try calling
ensure_connected
inside your begin/rescue/end block.