Jay Jay - 6 months ago 22
Ruby Question

Continue a loop after rescuing from an external API error in Rails

How can I use

rescue
to continue a loop. I’ll make an example

def self.execute
Foo.some_scope.each do |foo|
# This calls to an external API, and sometimes can raise an error if the account is not active
App::Client::Sync.new(foo).start!
end
end


So normally
rescue Bar::Web::Api::Error => e
would go at the end of the method and the loop will stop. If I could update a attribute of the
foo
that was rescued and call the method again, that
foo
would not be included in the scope and I would be able to start the loop again. But the issue with that is, I only want this once for each
foo
. So that way would loop through all of the existing
foo
again.

What’s another way I could do this? I could make a private method that is called at the top of the
execute
method. This could Loop through the
foo
and update the attribute so they aren’t part of the scope. But this sounds like an endless loop.

Does anyone have a good solution to this?

Answer

You can put a begin and rescue block within the loop. You talk about "updating an attribute of the foo" but it seems you only want that to ensure this foo is not processed on a restart of the loop, but you don't need to restart the loop.

def self.execute
  Foo.some_scope.each do |foo|
    # This calls to an external API, and sometimes can raise an error if the account is not active
    begin
      App::Client::Sync.new(foo).start!
    rescue Bar::Web::Api::Error
      foo.update(attribute: :new_value) # if you still need this
    end
  end
end