15

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?

B Seven
  • 44,484
  • 66
  • 240
  • 385

2 Answers2

16

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
Justin Wood
  • 9,941
  • 2
  • 33
  • 46
  • 2
    If you're re-raising an exception inside a rescue, you don't need to pass an argument: `raise if ENV["RACK_ENV"] == "test"; handle_error error` – Max Mar 27 '15 at 17:57
  • 1
    the problem here is that it changes the location of the error. – baash05 Nov 09 '17 at 03:07
3

You could always rescue it then then either handle or rethrow depending on your condition

begin
  do_something
rescue => error
  if ENV['RACK_ENV'] != 'test'
    handle_error error
  else
    raise error
  end
end
maerics
  • 151,642
  • 46
  • 269
  • 291