Joe Half Face Joe Half Face - 4 months ago 37
Ruby Question

Why including Rescuable module doesn't work?

class MyKlass

include ActiveSupport::Rescuable

rescue_from Exception do
return "rescued"

#other stuff

MyKlass is pure ruby object, but defined inside Rails application.

If I try to invoke MyKlass instance in rails console and then apply to it method which certainly should raise Exception, nothing happens other than error expected to be rescued.


Here is how it should be used:

class MyKlass
  include ActiveSupport::Rescuable
  # define a method, which will do something for you, when exception is caught
  rescue_from Exception, with: :my_rescue

  def some_method(&block)
  rescue Exception => exception
    rescue_with_handler(exception) || raise

  # do whatever you want with exception, for example, write it to logs
  def my_rescue(exception)
    puts "Exception catched! #{exception.class}: #{exception.message}"
end { 0 / 0 }
# Exception catched! ZeroDivisionError: divided by 0
#=> true

It goes without saying, that rescuing Exception is a crime.