如何在ActiveJob rescue中访问执行参数

时间:2015-03-16 19:34:05

标签: ruby-on-rails ruby ruby-on-rails-4 sidekiq rails-activejob

我想知道如何在救援区中访问ActiveJob执行参数,例如

def perform object
end

rescue_from Exception do |e|
   if e.class != ActiveRecord::RecordNotFound
      **job.arguments.first** 
      # do something
   end
end

谢谢!!

3 个答案:

答案 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

Why is it a bad style to `rescue Exception => e` in Ruby?

答案 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的绑定。这也可以考虑在内,但为了简洁起见。