How to access runtime options when rescuing ActiveJob

I am wondering how do you access ActiveJob to execute parameters in a resue block like

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

Thanks!

+7
ruby ruby-on-rails ruby-on-rails-4 sidekiq rails-activejob
source share
3 answers

In the rescue_from block rescue_from maybe << 20> << 20>:

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

This also works for callbacks (for example, inside after_perform ).

+6
source share

I also did not know about this, and then decided to try and use self inside the rescue_from block, and it worked.

 rescue_from(StandardError) do |ex| puts ex.inspect puts self.job_id # etc. end 

As a side note - NEVER save an Exception :

Why is this a bad style for `rescue Exception => e` in Ruby?

+2
source share

You can access all Bindings ex.bindings . To make sure that you are properly attached to your work, you should check the receiver as follows: 1 :

 method_binding = ex.bindings.find { |b| b.receiver.is_a?(self.class) } 

Then you can get all local variables with .local_variable_get . Since the method arguments are also local variables, you can at least get them explicitly:

 user = method_binding.local_variable_get(:user) post = method_binding.local_variable_get(:post) 

So for an example:

 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 

<sub> 1. It is still possible that this binding does not apply to perform if you call other instance methods in the task execution method and an error occurs there. This can also be taken into account, but not indicated for brevity.

+1
source share

All Articles