Search code examples
rubyexceptionrack

Is it possible to use rescue with a conditional?


Consider a Rack app. I only want to handle the error if we are not running a test:

begin
  do_something

  if ENV[ 'RACK_ENV' ] != 'test'
    rescue => error
      handle_error error
    end
  end
end

This generates syntax error, unexpected keyword_rescue (SyntaxError) rescue => error

Is there a way to do this?


Solution

  • Could you do something like this?

    begin
      do_something
    
    rescue => error
      if ENV["RACK_ENV"] == "test"
        raise error
      else
        handle_error error
      end
    end
    

    This would re-throw the exception if you are not testing.

    EDIT

    As @Max points out, you can be a little more succinct with this.

    begin
      do_something
    
    rescue => error
      raise if ENV["RACK_ENV"] == "test"
    
      handle_error error
    end