Skip to content

tiagofsilva/matching_exceptions

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MatchingExceptions

Build Status

Rescues exceptions using pattern matching.

Usage example:

  def foo
    raise StandardError.new('foo bar')
  rescue ME.matches(/bar/)
    puts 'it works!'
  end

  pry(main)> foo
  # it works!

An ideal use case for this gem:

Old code

  def bar
    do_something_complicated
  rescue StandardError => e
    if e.message =~ /some kind of error/
      treat_error
    else
      treat_rest
    end
  end

New code

  def bar
    do_something_complicated
  rescue ME.matches(/some kind of error/)
    treat_error
  rescue StandardError
    treat_rest
  end

Installation

Add this line to your application's Gemfile:

gem 'matching_exceptions'

And then execute:

$ bundle

Or install it yourself as:

$ gem install matching_exceptions

Usage

Call ME.matches(something) in a rescue block to rescue exceptions with something.

By default, message will be matched (i.e. the exception will be rescued if e.message == something, or e.message =~ something if something is a regex).

You can also specify a custom method with the keyword argument on::

  class CustomError < StandardError
    attr_reader :my_custom_method
  end

  ...

  begin
    raise CustomError.new('foo', 'some weird custom field')
  rescue ME.matches(/weird/, on: :my_custom_method)
    puts 'yay!'
  end

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/guava/matching_exceptions.

License

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

About

Allows exceptions to be pattern matched

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Ruby 97.7%
  • Shell 2.3%