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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With