kgpdeveloper
kgpdeveloper

Reputation: 2119

How to rescue timeout issues (Ruby, Rails)

most of my apps have a lot to do with web services and often due to the third party site, I get timeout issues.

This is the error that I get:

  execution expired
  /usr/lib/ruby/1.8/timeout.rb:54:in `rbuf_fill'

How do I rescue this kind of error in a rails app?

Upvotes: 12

Views: 22341

Answers (3)

Jonathan
Jonathan

Reputation: 16349

Use the awesome Rack::Timeout gem for your rack apps

Then use Simone's controller goodness

Upvotes: 4

xijo
xijo

Reputation: 4366

this is what I do in my rails apps:

# in ApplicationController
rescue_from Your::Exception, :with => :handle_exception

protected

def handle_exception
  # do anything you want here
end

You may specify the exception like you would do in a rescue clause of course.

Greetings, Joe

Upvotes: 2

Simone Carletti
Simone Carletti

Reputation: 176352

Depending on how you use the library, there are different ways to rescue the exception.

In the library

Assuming you created a wrapper to access some kind of web service, you can have the wrapper rescue the exception and always return a "safe" data.

In the action

If you call a specific method in the action and the method success is a requirement for the action, then you can rescue it in the action. In the following example I rescue the error and show a specific template to handle the problem.

def action
  perform_external_call
rescue Timeout::Error => e
  @error = e
  render :action => "error"
end

In the controller

If the method call can occur in many different actions, you might want to use rescue_from.

class TheController < ApplicationController

  rescue_from Timeout::Error, :with => :rescue_from_timeout

  protected

  def rescue_from_timeout(exception)
    # code to handle the issue
  end

end

Upvotes: 30

Related Questions