Giuseppe Solinas
Giuseppe Solinas

Reputation: 41

ActiveJob retry_on callback being ignored

I am running Rails 5.1, ruby 2.5, Sidekiq. I have set up a simple use case:

class RetryJobException < Exception

end

class CustomJob < ActiveJob::Base

    retry_on RetryJobException, wait: 3.seconds, attempts: 2 do
        puts "RETRYING"
    end

    def perform(*args)
        raise RetryJobException
    end
end

What happens here is that when I run this job and it raises RetryJobException, CustomJob is re-ran after 30 seconds (and not three...) for an indefinite number of times (and not 2), until I kill Sidekiq's process. "RETRYING" is never printed anywhere, which is a sign that the code within the retry_on block is never executed.

According to the documentation this should be a basic use case, yet, I am having these issues. What am I doing wrong?

Upvotes: 4

Views: 1606

Answers (2)

channa ly
channa ly

Reputation: 9937

After reading the documention carefully, I've found this:

You can also pass a block that'll be invoked if the retry attempts fail for custom logic rather than letting the exception bubble up. This block is yielded with the job instance as the first and the error instance as the second parameter.

retry_on allows a block to be passed for handling the exception once the retry attempts have been exhausted.

My scenario is to notify me if the job fails, rescue_from seems to solve my problem

module LoggableJob
  extend ActiveSupport::Concern

  included do
    rescue_from(StandardError) do |exception|
      ExceptionNotifier.notify_exception(exception, data: job_exception_data)
      AppLog.exception(exception, self, data: job_exception_data)

      # https://apidock.com/rails/v5.0.0.1/ActiveJob/Enqueuing/retry_job
      retry_job wait: 5.minutes, priority: 5
    end
  end

  def job_exception_data
    { queue_name: queue_name, args: arguments, job_id: job_id}
  end
end

Upvotes: 0

Helio Albano
Helio Albano

Reputation: 917

This worked to me:

class RetryJobException < Exception

end

class UnprocessableJob < StandardError; end

class CustomJob < ActiveJob::Base

    retry_on RetryJobException, wait: 3.seconds, attempts: 2 do
        puts "RETRYING"
        before_perform { raise UnprocessableJob }
    end

    discard_on UnprocessableJob

    def perform(*args)
        raise RetryJobException
    end
end

Upvotes: 0

Related Questions