Reputation: 47
When coding in Ruby, I frequently write something like this
def someopp(param)
r_val = nil
begin
r_val = do_something(param)
rescue Some::Error => e
r_val = {}
end
r_val
end
I don't like the looks of it. Declaring the return variable that doesn't really do anything, then a line again with just the var name in order to return it. It's cumbersome. I feel that, in Ruby, there must be way to make it more clean and pretty. Any suggestion for syntactic sugar over here?
Upvotes: 1
Views: 288
Reputation: 16667
If you're really doing this exact thing very frequently (calling external dependencies that can raise exceptions and falling back to some default value), can generalize further:
def rescuing(*exceptions, with:)
yield
rescue *exceptions
with
end
value = rescuing(ZeroDivisionError, with: Float::INFINITY) { 3 / 0 }
# => Infinity
Though it would be better still if you could avoid the exceptions to begin with, if possible.
Upvotes: 0
Reputation: 1714
def someopp(param)
do_something(param)
rescue Some::Error
{}
end
or
def someopp(param)
do_something(param) rescue {}
end
But not recomend to use inline-rescue!
Upvotes: 7