https://github.com/ktchen14/rescue-with
Adds `... rescue ExceptionType.with { ... }` to Ruby
https://github.com/ktchen14/rescue-with
ruby
Last synced: 7 months ago
JSON representation
Adds `... rescue ExceptionType.with { ... }` to Ruby
- Host: GitHub
- URL: https://github.com/ktchen14/rescue-with
- Owner: ktchen14
- License: unlicense
- Created: 2018-03-30T02:00:28.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2018-04-09T07:38:08.000Z (about 8 years ago)
- Last Synced: 2025-07-05T00:29:54.502Z (10 months ago)
- Topics: ruby
- Language: Ruby
- Homepage:
- Size: 4.88 KB
- Stars: 13
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# rescue-with
Inline rescue a specific exception type in Ruby.
## Background
The modifier form of `rescue` in Ruby
[can](https://github.com/bbatsov/ruby-style-guide#no-rescue-modifiers)
[be](https://rubocop.readthedocs.io/en/latest/cops_style/#stylerescuemodifier)
[dangerous](https://www.rubytapas.com/2012/11/12/episode-022-inline-rescue/)
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](https://bugs.ruby-lang.org/issues/6739) from 2013.
## Installation
```
gem install rescue-with
```
## Usage
To use this gem required it with:
```ruby
require 'rescue-with'
```
This gem adds the syntax:
```ruby
... 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:
```ruby
... rescue ExceptionType.with { |e| ... }
```
## Example
Output an error message to `stderr` if a file can't be read:
```ruby
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 `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.
## License
The gem is available as open source under the terms of [The
Unlicense](http://unlicense.org/).