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 catched! #{exception.class}: #{exception.message}"
end
end
MyKlass.new.some_method { 0 / 0 }
# Exception catched! ZeroDivisionError: divided by 0
#=> true
It goes without saying, that rescuing Exception
is a crime.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.