Skip to content

Instantly share code, notes, and snippets.

@caius
Last active January 16, 2024 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caius/efdf1cabd2947ca55bf6e88d9f9e95bf to your computer and use it in GitHub Desktop.
Save caius/efdf1cabd2947ca55bf6e88d9f9e95bf to your computer and use it in GitHub Desktop.
ActiveJob::Base.queue_adapter = :delayed
$stdout.sync = true
$stdout.flush
class MyBaseJob < ActiveJob::Base
# Stop delayed retrying at all
def max_attempts
0
end
def job_flailed
puts "[#{self.class}] #job_flailed called"
# TODO: Implement attached item logic here to clean up
end
# Public: Delayed::Base callback for error from #perform
#
# Called when Exception is raised, or ActiveJob hasn't handled error already. The ActiveJob instance
# can be accessed through `job.payload_object`.
#
# @param job [Delayed::Job] the job that failed
# @param exception [Exception] the exception that was raised
def error(job, exception)
puts "[#{self.class}] #error called"
job_flailed
end
# Override: ActiveJob::Execution#rescue_with_handler
#
# Called when StandardError or subclasses are raised during job's #perform method. Called on every attempt
# that raises an error.
#
# This MUST return the result of calling super to maintain existing behaviour.
def rescue_with_handler(...)
puts "[#{self.class}] #rescue_with_handler called"
result = super(...)
# If the job is being retried, it has `scheduled_at` set to truthy value
unless scheduled_at
job_flailed
end
result
end
end
class MySensibleJob < MyBaseJob
CustomError = Class.new(StandardError)
retry_on CustomError, wait: 0, attempts: 2 do
puts "[MySensibleJob] CustomError retry_on block called"
end
def perform
puts
puts "[MySensibleJob] #perform"
raise CustomError
end
end
class MyNaughtyJob < MyBaseJob
discard_on StandardError
def perform
puts
puts "[MyNaughtyJob] #perform"
raise StandardError
end
end
class MyBatshitJob < MyBaseJob
def perform
puts
puts "[MyBatshitJob] #perform"
raise Exception
end
end
MySensibleJob.perform_later
MyNaughtyJob.perform_later
MyBatshitJob.perform_later
Delayed::Worker.new.work_off
sleep 5
$ bin/rails runner tmp/my-jobs.rb
[MySensibleJob] #perform
[MySensibleJob] #rescue_with_handler called
[MyNaughtyJob] #perform
[MyNaughtyJob] #rescue_with_handler called
[MyNaughtyJob] #job_flailed called
[MyBatshitJob] #perform
[MyBatshitJob] #error called
[MyBatshitJob] #job_flailed called
[MySensibleJob] #perform
[MySensibleJob] #rescue_with_handler called
[MySensibleJob] CustomError retry_on block called
[MySensibleJob] #job_flailed called
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment