如何解决超时问题(Ruby,Rails)

我的大多数应用程序都与Web服务有很大关系,并且通常由于第三方站点,我会遇到超时问题。

这是我得到的错误:

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

如何在rails应用程序中挽救此类错误?

根据您使用库的方式,有不同的方法来挽救exception。

在图书馆

假设您创建了一个包装器来访问某种Web服务,您可以让包装器解除exception并始终返回“安全”数据。

在行动中

如果您在操作中调用特定方法并且方法成功是操作的要求,那么您可以在操作中挽救它。 在下面的示例中,我解除了错误并显示了一个特定的模板来处理问题。

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

在控制器中

如果方法调用可以在许多不同的操作中发生,则可能需要使用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 

为您的机架应用程序使用超棒的Rack :: Timeout gem

然后使用Simone的控制器优点

这就是我在rails应用程序中所做的事情:

 # in ApplicationController rescue_from Your::Exception, :with => :handle_exception protected def handle_exception # do anything you want here end 

您可以像在救援条款中那样指定例外。

问候,乔