Add salvation to every method inside the class

class A def a_method #.. end end class B < A def method_1 # ... a_method end def method_2 # ... a_method end # ... def method_n # ... a_method end end 

a_method throws an AException.

I want to get rid of this exception, for example:

 class B < A def method_1 # ... a_method rescue AException => e p e.message end # ... end 

I want to save the same path in every method inside class B ( method_1 , method_2 , ..., method_n ). I was stuck looking for a clean and clean solution that did not require duplication of the rescue code block. Can you help me?

+5
source share
4 answers

How to use the block:

 class B < A def method_1 # some code here which do not raised an exception with_rescue do # method which raised exception a_method end end def method_2 with_rescue do # ... a_method end end private def with_rescue yield rescue => e ... end end 
+6
source

How is this possible?

 class B < A def method_1 # ... safe_a_method end private def safe_a_method a_method rescue AException => e ... end end 
+5
source

If you want to always save the exception, you can simply override a_method in B :

 class B < A def a_method super rescue AException => e p e.message end # ... end 

Alternatively, you can return a value (e.g. nil or false ) to indicate a failure.

+5
source

You can wrap your methods with a module like this. The advantage is that, unlike other solutions that you can call your methods with their usual names, the methods themselves do not need to be changed. Just extend the class with the ErrorHandler en method at the end, list the methods to wrap them with error handling logic.

 module ErrorHandler def wrap(method) old = "_#{method}".to_sym alias_method old, method define_method method do |*args| begin send(old, *args) rescue => e puts "ERROR FROM ERRORHANDLER #{e.message}" end end end end class A extend ErrorHandler def a_method v "a_method gives #{v.length}" end (self.instance_methods - Object.methods).each {|method| wrap method} end class B < A extend ErrorHandler def method_1 v "method_1 gives #{v.length}" end (self.instance_methods - Object.methods).each {|method| wrap method} end puts A.new.a_method "aa" # a_method gives 2 puts A.new.a_method 1 # ERROR FROM ERRORHANDLER undefined method `length' for 1:Fixnum puts B.new.method_1 1 # ERROR FROM ERRORHANDLER undefined method `length' for 1:Fixnum 
+1
source

All Articles