Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why including Rescuable module doesn't work?

class MyKlass

  include ActiveSupport::Rescuable

  rescue_from Exception do
    return "rescued"
  end

  #other stuff
end

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.

like image 829
Joe Half Face Avatar asked Oct 16 '25 16:10

Joe Half Face


1 Answers

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)
    yield
  rescue Exception => exception
    rescue_with_handler(exception) || raise
  end

  # do whatever you want with exception, for example, write it to logs
  def my_rescue(exception)
    puts "Exception caught! #{exception.class}: #{exception.message}"
  end
end

MyKlass.new.some_method { 0 / 0 }
# Exception caught! ZeroDivisionError: divided by 0
#=> true

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

like image 151
Andrey Deineko Avatar answered Oct 18 '25 07:10

Andrey Deineko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!