Redis lookup with a default value I have some code to perform a redis lookup, but if the key to look up either doesn't exist or there's an issue connecting to Redis at all, it will use a default value.

The logic currently looks like this:

begin
 redis = Redis.new(:url =&gt; url)
 returned_value = redis.get(key)
 if returned_value == nil and defined?(default) != nil
   default
 else
   returned_value
 end
rescue Exception =&gt; e
  if default
    debug "Connection to redis failed with #{e} - Returning default value of #{default}"
    default
  else
    raise(Puppet::Error, "connection to redis server failed - #{e}")
  end
end


It feels like there might be a simpler way of doing this, right now this code feels a little wordy.

Any suggestions?
First of all NEVER rescue ExceptionError. If you want a to rescue from any runtime exception, just omit exception class, otherwise you might catch SignalException which happens upon ruby process received some signal (e.g. SIGTERM) and instead of behave correctly you will silently skip that.

So, your rescue part should look actually like this:

begin
  # ...
rescue SocketError, Redis::CannotConnectError =&gt; e
  raise Puppet::Error, "connection to redis server failed - #{e}" unless default
  debug "Connection to redis failed with #{e} - Returning default value of #{default}"
  default
end


Now your main block can be also improved:

begin
  Redis.new(:url =&gt; url).get(key) || default
rescue
  # ...
end


Notice that redis returns either String or Nil, e.g.:

Redis.current.set(:x, 123)
Redis.current.get(:x) # =&gt; "123"

Redis.current.set(:x, false)
Redis.current.get(:x) # =&gt; "false"


So, summing all above together, you can form that into a method:

def redis_get(key, url:, default: nil)
  Redis.new(:url =&gt; url).get(key) || default
rescue SocketError, Redis::CannotConnectError =&gt; e
  raise Puppet::Error, "connection to redis server failed - #{e}" unless default
  debug "Connection to redis failed with #{e}; Return default: #{default}"
  default
end