To centralize the error handling of my application, I created the class ErrorHandling. This class should log all my errors, notify me via Slack, etc.
class ErrorHandler
def self.handle_error
yield
rescue => e
log_error(e.message)
notify_via_slack(e.message)
# etc.
end
end
I need to wrap all the methods of MyClass manually within ErrorHandler.handle_error to make use of the central error handling.
class MyClass
def method1
ErrorHandler.handle_error do
raise StandardError, 'my error msg'
end
end
def method2
ErrorHandler.handle_error do
raise StandardError, 'my error msg'
end
end
end
This will pollute my code unnecessarily. I thought about dynamically overriding my methods, so I don't have to wrap them manually.
class MyClass
def method1
raise StandardError, 'my error msg'
end
def method2
raise StandardError, 'my error msg'
end
instance_methods(false).each do |method_name| # instance_methods(false) => [:method1, :method2]
define_method(method_name) do
ErrorHandler.handle_error do
super()
end
end
end
end
Unfortunately this code won't work. Is it possible to dynamically override the methods of MyClass?
My goal is to dynamically override all instance methods of a class to make use of the central error handling, so I don't have to manually modify every method.
Thanks for your help!