【问题标题】:Ruby on Rails 5 ActiveJob retry_on, discard_on catch exception orderRuby on Rails 5 ActiveJob retry_on、discard_on 捕获异常顺序
【发布时间】:2018-12-03 19:13:44
【问题描述】:

我正在使用 ActiveJob,但我对用于捕获异常的方法 discard_on 和 retry_on 有一些疑问。

  1. ActiveJob 是否定义了它们的顺序和执行顺序? (我猜它是相关的,但我不确定。)

  2. 假设相关,希望retry_on只捕获自定义异常,其他异常被discard_on捕获。

我看到source code中的discard_on和retry_on是使用rescue_from,因为rescue_from定义语句后要先执行所以这里是我自己假设定义的方式,希望大家能帮我指出是否是对,当然,如果你有更好的方法来实现相同的功能,请告诉我,非常感谢。

class RemoteServiceJob < ActiveJob::Base      
  discard_on StandardError # second catch other exceptions
  retry_on MyCustomException, wait: 5.seconds, attempts: 3 # first catch custom exceptions
end

【问题讨论】:

    标签: ruby-on-rails rails-activejob ruby-on-rails-5.2


    【解决方案1】:

    在我的测试中,执行顺序和我预想的完全一样,因为rescue_from的声明顺序是相反的,异常声明的顺序也需要一致。

    def discard_on(exception)
      rescue_from exception do |error|
        if block_given?
          yield self, error
        else
          logger.error "Discarded #{self.class} due to a #{exception}. The original exception was #{error.cause.inspect}."
        end
      end
    end
    
    def retry_on(exception, wait: 3.seconds, attempts: 5, queue: nil, priority: nil)
      rescue_from exception do |error|
        if executions < attempts
          logger.error "Retrying #{self.class} in #{wait} seconds, due to a #{exception}. The original exception was #{error.cause.inspect}."
          retry_job wait: determine_delay(wait), queue: queue, priority: priority
        else
          if block_given?
            yield self, error
          else
            logger.error "Stopped retrying #{self.class} due to a #{exception}, which reoccurred on #{executions} attempts. The original exception was #{error.cause.inspect}."
            raise error
          end
        end
      end
    end
    

    【讨论】:

      猜你喜欢
      • 2015-10-19
      • 1970-01-01
      • 2016-10-29
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多