首页 > 解决方案 > 没有在 Rails 中捕获独角兽超时异常

问题描述

这是我试图处理来自独角兽的异常的示例代码。

unicron.rb

worker_processes Integer(ENV['WEB_CONCURRENCY'] || 3)
timeout 15
preload_app true

超时.rb

Rack::Timeout.timeout = 12

示例代码

def create_store
   ActiveRecord::Base.transaction do

     @store = Store.new(params[:store])
     if @store.save!
       sleep 12.3
       InformUserWorker.perform_async(store_id)
     end

   end

   rescue => exception
    exception.backtrace.each { |trace| puts trace }
   rescue Timeout::Error
    puts 'That took too long, exiting...1'
   rescue Rack::Timeout::RequestTimeoutException
    puts 'That took too long, exiting...2'
   rescue Rack::Timeout::RequestTimeoutError
    puts 'That took too long, exiting...3'
   rescue Rack::Timeout::RequestExpiryError
    puts 'That took too long, exiting...4'
end

code=H13 desc="Connection closed without response"睡了 12.3 秒,事务回滚发生了,但是这些异常都没有执行。我在这里添加了几个例外。这里有什么问题吗?

标签: ruby-on-railsrubyruby-on-rails-3heroku

解决方案


救援按顺序执行。因此,您的第一次救援捕获了正在引发的任何内容,并且代码永远不会超过那个点。

试着把它放在最后:

 # other rescues in here.
 rescue => exception
  exception.backtrace.each { |trace| puts trace }
 end # this one is the last, only executed if none of the others are

如果问题是您不确定正在引发哪个类,只需使用 pry 之类的东西来调试exception.class


推荐阅读