Rescue_from doesn't rescue Timeout::Error from views or helpers

依然范特西╮ 提交于 2019-12-05 18:38:20

I ran into the same problem. I'm using Rails 3 + Rack::Timeout and trying to rescue_from in ApplicationController.

I ended up using this ...

rescue_from Exception do |exception|
  if exception.is_a?(Timeout::Error) || /execution expired/ =~ exception.message
    # rescued from timeout error
  end
  raise
end

UPDATE

I patched the rack-timeout gem to properly return Timeout::Error. It was a threading issue. Official gem has been updated: https://github.com/kch/rack-timeout

The new preferred method is below. In general, it's not a great idea to rescue from Exception and should be avoided if possible.

class ApplicationController < ActionController::Base
  rescue_from Timeout::Error, with: :handle_timeout

  def handle_timeout(exception)
    # handle timeout error
  end
end

When Timeout needs to raise an exception to terminate execution, it does not raise Timeout::Error. If it did, garden-variety rescues would trap it, and that's not what you want. Instead, it raises its own Exception that is derived from ::Exception, so it blows through any rescue except for rescue Exception. Or - you can pass your own Exception as the second parameter to Timeout::timeout, and that way you can rescue it. Note that Timeout will re-raise it.

Read the timeout.rb code (in ruby200/lib/ruby/2.0.0). It's quite short, pretty interesting and will tell you how it really works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!