John Bachir
John Bachir

Reputation: 22751

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

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.

Upvotes: 0

Views: 170

Answers (3)

sawa
sawa

Reputation: 168249

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

hash.fetch(key, DataError.new)

Upvotes: 1

Mori
Mori

Reputation: 27789

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

Upvotes: 0

Omnaest
Omnaest

Reputation: 3096

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...

Upvotes: 1

Related Questions