【问题标题】:How to access perform parameters in ActiveJob rescue如何在 ActiveJob 救援中访问执行参数
【发布时间】:2015-05-19 01:50:44
【问题描述】:

我想知道如何在resue块中访问ActiveJob执行参数,例如

def perform object
end

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

谢谢!!

【问题讨论】:

  • 异常发生在哪里?在执行方法中?如果是这样,只需将救援块放在 perform 方法中的罪魁祸首代码下方。您将可以访问作为局部变量的 object 参数。
  • Noz,我有 before_enqueue 和 around_perform 以及因此的 rescue_from。
  • 我以前没有使用过任何一个,但是你能不能把你的救援块放在这些块中?我认为您不想在 ActiveJob 中使用 rescue_from,一个简单的 rescue ActoveRecord::RecordNotFound => e 就足够了。
  • 在 ActiveJobs 中使用 rescue_from 绝对支持(并且很有帮助):edgeguides.rubyonrails.org/active_job_basics.html#exceptions 具体来说,它在 Job 基类中非常有用(类似的故障可以合并到一个 rescue_from而不是复制到十几个 perform 块中)。

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


【解决方案1】:

我也对此一无所知,然后决定尝试在 rescue_from 块内使用 self,它成功了。

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】:

arguments 可以在 rescue_from 块内使用:

rescue_from(StandardError) do |exception|
  user = arguments[0]
  post = arguments[1]
  # ...      
end

def perform(user, post)
  # ...
end

这也适用于回调(例如,在 after_perform 内部)。

【讨论】:

  • 谢谢,这对我有用(Rails 5.0.1,sidekiq 4.2.9)。在rescue_from 块中,arguments[0] 给了我传递给perform 的第一个参数。
【解决方案3】:

您可以通过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 方法中调用其他实例方法并且错误发生在那里,则此绑定仍然可能不是 perform 之一。这也可以考虑在内,但为简洁起见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多