Skip to content

Adds `... rescue ExceptionType.with { ... }` to Ruby

License

Notifications You must be signed in to change notification settings

ktchen14/rescue-with

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

rescue-with

Inline rescue a specific exception type in Ruby.

Background

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.

Installation

gem install rescue-with

Usage

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| ... }

Example

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') }

Caveats

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 Exceptions 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.

License

The gem is available as open source under the terms of The Unlicense.

About

Adds `... rescue ExceptionType.with { ... }` to Ruby

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages