开发者

How can I handle exceptions in exactly the same way for a set of methods?

开发者 https://www.devze.com 2023-03-11 10:17 出处:网络
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.

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开发者_JAVA技巧 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.


If you want to handle the error in a central way, maybe your methods should not throw an error, instead catching errors and transport them e.g. to a

  • central listener which takes the errors and dispatches them, or
  • a handler which does something based on the error...


If you want to return DataError when hash lacks key, you can do:

hash.fetch(key, DataError.new)


rescue_from only 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:

class Foo
  def m1
    m 1
  end

  def m2
    m 2
  end

  def m(arg)
    begin
      # try
    rescue
      # handle error
    end
  end
end

or use method_missing to handle all of those method calls, and handle errors there:

class Foo
  def method_missing(method, *args, block)
    (super and return) unless method =~ /whatever/
    begin
      #try
    rescue
      # handle error
    end
  end
end
0

精彩评论

暂无评论...
验证码 换一张
取 消