我想知道如何在救援区中访问ActiveJob执行参数,例如
def perform object
end
rescue_from Exception do |e|
if e.class != ActiveRecord::RecordNotFound
**job.arguments.first**
# do something
end
end
谢谢!!
答案 0 :(得分:9)
arguments
块内rescue_from
可以使用
rescue_from(StandardError) do |exception|
user = arguments[0]
post = arguments[1]
# ...
end
def perform(user, post)
# ...
end
这也适用于回调(例如在after_perform
内)。
答案 1 :(得分:2)
我也不知道这一点,然后只是决定尝试在self
块内使用rescue_from
,它就有用了。
rescue_from(StandardError) do |ex|
puts ex.inspect
puts self.job_id
# etc.
end
作为旁注 - 永远不要拯救Exception
:
答案 2 :(得分:1)
您可以ex.bindings
访问所有Bindings。为确保您获得正确的工作绑定,您应该检查接收器,如 1 :
method_binding = ex.bindings.find { |b| b.receiver.is_a?(self.class) }
然后,您可以使用.local_variable_get
获取所有局部变量。由于方法参数也是局部变量,因此至少可以显式获取它们:
user = method_binding.local_variable_get(:user)
post = method_binding.local_variable_get(:post)
所以对你来说:
def perform object
end
rescue_from Exception do |e|
if e.class != ActiveRecord::RecordNotFound
method_binding = ex.bindings.find { |b| b.receiver.is_a?(self.class) }
object = method_binding.local_variable_get(:object)
# do something
end
end
<子> 1。如果在作业执行方法中调用其他实例方法并且错误发生在那里,那么此绑定仍然可能不是perform
的绑定。这也可以考虑在内,但为了简洁起见。