Search code examples
ruby-on-railsrubytimeoutsavon

How to define a class wide rescue method for Timeout::error?


I have a class that uses savon as a gem to speak with a SOAP API. And from times to times the server is unreachable so the methods that implement the soap methods throw a Timeout::Error. Its not a problem to implement a rescue like this:

begin 
  ...
rescue Timeour::Error 
  ...
end

But I have ~50 methods defined that might be affected and I dont want to repeat the same code 50 times. Thats abolutely not dry. Is there a way to deal with this? I already thought about sth like this:

def safe_call method, params
  begin
    self.send method, params
  rescue Timeour::Error
    # do sth heroic to rescue the method
  end
end

But thats pretty unawesome because I have to change each call in all scripts that use the class. Is there a way to do a class wide rescue?


Solution

  • I think you can use rescue_from. You can read about it here: http://api.rubyonrails.org/classes/ActiveSupport/Rescuable/ClassMethods.html

    In short, you can put this in your application controller:

    rescue_from 'Timeout::Error' do |exception|
      # Rescue logic here.
    end