Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 266
B Seven Avatar asked Mar 27 '15 17:03

B Seven


People also ask

Can we use rescue without begin?

The method definition itself does the work of begin , so you can omit it. You can also do this with blocks. Now, there is one more way to use the rescue keyword without begin .

What does Ruby Rescue do?

In Ruby, we use the rescue keyword for that. When rescuing an exception in Ruby, you can specify a specific error class that should be rescued from. Note: When using raise without specifying an exception class, Ruby will default to RuntimeError .

How do you handle exceptions in Rails?

Exception handling in Ruby on Rails is similar to exception handling in Ruby. Which means, we enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.

How do you raise exceptions in Ruby?

You can capture an exception using rescue block and then use retry statement to execute begin block from the beginning.


2 Answers

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
like image 94
Justin Wood Avatar answered Nov 14 '22 09:11

Justin Wood


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
like image 42
maerics Avatar answered Nov 14 '22 07:11

maerics