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