Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent ActiveJob from performing if the object it should perform on is deleted?

I have a background job that does some work on uploaded images, but sometimes the image is deleted by the user before the background job is performed, and it creates an ActiveJob::DeserializationError

Is there something I can do in the model in before_destroy to cancel the job? Or something in the job class I can do in before_perform to not execute the job if the record has been deleted in the database?

Thanks!

like image 425
Mason Avatar asked Oct 16 '25 16:10

Mason


1 Answers

Active job instances include ActiveSupport::Rescuable which means you can use rescue_from in a job in the same way you can in a controller.

You can then recover from any deserialization error:

class MyJob < ApplicationJob

  rescue_from(ActiveJob::DeserializationError) do |e|
    true 
  end

end

If you want to use this pattern in a lot of jobs you could extract it to a module:

module DeserializationErrorIsOkay

  extend ActiveSupport::Concern

  included do
    rescue_from(ActiveJob::DeserializationError) do |e|
      # This error is okay and doesn't indicate a failed job
      true
    end
  end

end

which you can just include in your jobs:

class MyJob < ApplicationJob
  include DeserializationErrorIsOkay
end

NB: this recovers from any of the objects being serialized in the job failing to be deserialized

like image 152
Shadwell Avatar answered Oct 18 '25 06:10

Shadwell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!