如何处理 'record does not exist' 错误并防止后台作业尝试重试?
How to handle 'record does not exist' errors and prevent background jobs from attempting retries?
一个 Rails 应用有一个调用服务对象的后台作业,如下所示
class ObjectUpdateJob < ActiveJob::Base
queue_as :default
def perform(object_id)
ObjectUpdater.call(object_id)
end
end
class ObjectUpdater
def self.call(*args)
if @object = Object.find( args[:object_id] )
#... update some stuff from external services
else
#... raise an error and prevent the background job from attempting to retry
end
end
end
这可能是一个简单的问题,但我在错误处理方面的经验有限,我希望能再考虑一下。
处理此 'record does not exist' 案例并确保通知后台作业以便不重试的 'Rails way' 是什么?
您可以在工人的 perform
操作中加入保护条款:
class ObjectUpdateJob < ActiveJob::Base
queue_as :default
def perform(object_id)
return unless Object.find(object_id)
ObjectUpdater.call(object_id)
end
end
但为了获得更多保护,您可以对作业调用进行一些检查:
ObjectUpdateJob.perform_now(object_id) if Object.find(object_id)
这样你就不会让不存在的对象被处理。
如果您使用 Sidekiq,您可以将标志设置为 :retry => false
,这样作业就不会自动重试。
此外,Sidekiq 内置了错误处理机制。以下是有关此事的更多信息:https://github.com/mperham/sidekiq/wiki/Error-Handling
希望对您有所帮助。
一个 Rails 应用有一个调用服务对象的后台作业,如下所示
class ObjectUpdateJob < ActiveJob::Base
queue_as :default
def perform(object_id)
ObjectUpdater.call(object_id)
end
end
class ObjectUpdater
def self.call(*args)
if @object = Object.find( args[:object_id] )
#... update some stuff from external services
else
#... raise an error and prevent the background job from attempting to retry
end
end
end
这可能是一个简单的问题,但我在错误处理方面的经验有限,我希望能再考虑一下。
处理此 'record does not exist' 案例并确保通知后台作业以便不重试的 'Rails way' 是什么?
您可以在工人的 perform
操作中加入保护条款:
class ObjectUpdateJob < ActiveJob::Base
queue_as :default
def perform(object_id)
return unless Object.find(object_id)
ObjectUpdater.call(object_id)
end
end
但为了获得更多保护,您可以对作业调用进行一些检查:
ObjectUpdateJob.perform_now(object_id) if Object.find(object_id)
这样你就不会让不存在的对象被处理。
如果您使用 Sidekiq,您可以将标志设置为 :retry => false
,这样作业就不会自动重试。
此外,Sidekiq 内置了错误处理机制。以下是有关此事的更多信息:https://github.com/mperham/sidekiq/wiki/Error-Handling
希望对您有所帮助。