Inline rescue a specific exception type in Ruby.
The modifier form of rescue
in Ruby
can
be
dangerous
because it rescues from StandardError
and can't be targeted toward a more
specific exception. To rescue from a specific exception the full begin ... rescue ... end
syntax must be used which can be needlessly verbose as evident
from this proposal from 2013.
gem install rescue-with
To use this gem required it with:
require 'rescue-with'
This gem adds the syntax:
... rescue ExceptionType.with { ... }
To rescue from ExceptionType
and return the result { ... }
. If you need the
exception itself and don't want to use $!
then do:
... rescue ExceptionType.with { |e| ... }
Output an error message to stderr
if a file can't be read:
data = File.read('none') rescue Errno::ENOENT.with { $stderr.puts('No data') }
Because the modifier form of rescue
only rescues from StandardError
this
syntax only works if StandardError
is an ancestor of ExceptionType
. This
shouldn't be a problem most of the time as Exception
s that aren't a subclass
of StandardError
are rarely rescued.
Note that StandardError#with
only rescues a single type of exception. If you
need to rescue multiple types of exceptions it's much better to use the begin ... rescue ... end
syntax.
The gem is available as open source under the terms of The Unlicense.