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?
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 .
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 .
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.
You can capture an exception using rescue block and then use retry statement to execute begin block from the beginning.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With