I’m building an api wrapper library. There are a set of methods are are simple “getters”, that go into certain hashes and pull out strings.
For all of these, there might be a nil hash or some other data problem (not network problems, I’m handling those elsewhere). If such a problem is encountered, I want to raise a DataError exception and then handle those exceptions in the user interface. So I have a handle_data_error method which accepts a block, and if the block raises an error, I catch it and raise a DataError.
Is there any way to elegantly wrap the entire contents of a set of methods in this method, without having to type it in there 15 times? Any way to tell a class “handle these sorts of errors this way”? It occurs to me maybe I should look at the implementation of Rails’ rescue_from.
rescue_fromonly works in controllers.When you have a lot of similar methods you can refactor them to either call a common core method where you handle errors:
or use
method_missingto handle all of those method calls, and handle errors there: