【问题标题】:Rufus Scheduler - Catch exception and perform conditional statementRufus Scheduler - 捕获异常并执行条件语句
【发布时间】:2012-11-07 19:06:18
【问题描述】:

我有一个 rufus 调度程序,它每 10 分钟执行一次对 Dropbox 的请求,检查访问密钥和密钥是否被授权。

如果未授权,则报如下异常:

DropboxAuthError in GalleryController#index

#<Net::HTTPUnauthorized:0x7ef04c8>

我在调度程序中检测到这一点的代码来自 rufus-scheduler 文档:

def scheduler.on_exception(job, exception)
  puts "job #{job.job_id} caught exception '#{exception}'"
end

因为我只想捕获上面的那个异常,所以我希望能够执行一个条件语句,将异常与一个值进行比较,例如:

 def scheduler.on_exception(job, exception)
  if exception == "DropboxAuthError"
    puts "job #{job.job_id} caught exception '#{exception}'"
  end
 end

但是因为异常是一个对象,所以我不能做那个比较。

有人知道我该怎么做吗?

非常感谢。

【问题讨论】:

    标签: ruby exception dropbox conditional-statements rufus-scheduler


    【解决方案1】:

    给猫剥皮的多种方法

    if exception.message.match(/DropboxAuthError/)
      # ...
    end
    
    if exception.is_a?(Net::HTTPUnauthorized)
      # ...
    end
    

    不要害怕你的 Ruby 对象。

    请注意,您可以避免从 rufus-scheduler 文档中选择的全局错误处理,并执行以下操作:

    scheduler.every '10m' do
      begin
        # do the API call...
      rescue Net::HTTPUnauthorized => ne
        puts "not authorized"
      rescue => e
        puts "something wrong happened " + e.inspect
      end  
    end
    

    rescue 在哪里为你做类型检查。

    干杯。

    【讨论】:

      猜你喜欢
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 1970-01-01
      相关资源
      最近更新 更多