How to extend ActiveJob to access delayed_job's failure/error hooks?

940 views Asked by At

I'm using rails ActiveJob's delayed_job adaptor, but would like to still be able to access delayed_job's error and failure hooks to trigger notification mailers when a job errors or fails.

I think I've tracked down the piece of ActiveJob code I need to extend in order to incorporate delayed_job's error and failure methods.

How do I go about extending the JobWrapper class below to include delayed_job's error and failure methods, so I can then use custom error/failure code on a job-by-job basis?

require "delayed_job"

module ActiveJob

  module QueueAdapters

    class DelayedJobAdapter

      def enqueue(job)
        delayed_job = Delayed::Job.enqueue(JobWrapper.new(job.serialize), queue: job.queue_name, priority: job.priority)
        job.provider_job_id = delayed_job.id
        delayed_job
      end

      def enqueue_at(job, timestamp)
        delayed_job = Delayed::Job.enqueue(JobWrapper.new(job.serialize), queue: job.queue_name, priority: job.priority, run_at: Time.at(timestamp))
        job.provider_job_id = delayed_job.id
        delayed_job
      end

      class JobWrapper
        attr_accessor :job_data

        def initialize(job_data)
          @job_data = job_data
        end

        def perform
          Base.execute(job_data)
        end
      end
    end
  end
end
2

There are 2 answers

1
Cristian Bica On

ActiveJob implements ActiveSupport::Rescuable which means you can use rescue_from.

class MyJob < ActiveJob::Base

  rescue_from Exception do |e|
    # do something with e
  end

  # rest of your job

end
0
Jin.X On

I believe this is what you want

module ActiveJob
  module QueueAdapters
    class DelayedJobAdapter
      class JobWrapper
        def failure(job)
          job_data = Base.deserialize(job.payload_object.job_data)
          job_data.failure(job) if job_data.respond_to?(:failure)
        end
      end
    end
  end
end

I've posted this problem/patch to rails issue https://github.com/rails/rails/issues/30205