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
peter source share