2

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

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

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

我在源码中看到discard_on和retry_on是使用rescue_from,因为recovery_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
4

1 回答 1

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
于 2018-07-05T08:51:26.513 回答