How to retry when exceptions happens in Ruby on Rails

How to retry when exceptions happens in Ruby on Rails

A really simple retry when exceptions happen in Ruby on Rails as in this example I’m using a `find_by` from ActiveRecord ORM.

  @tries = 5
  def find_this_guy
    sleep 5
    my_record = MyModel.find_by!(id: 66, other_boolean_field: true)
    Rails.logger.error "==== Success ====" if my_record
  rescue Exception => e
    Rails.logger.error e.to_s.red
    @tries -= 1
    if @tries > 0
      Rails.logger.debug 'Searching this guy'.yellow
      find_this_guy
    else
      Rails.logger.error "Error: #{e}".red
      raise e
    end
  end

If we run that method in the Rails console, we will see a few attempts to find that record and it will retry 5 times, in case we want to see the `Success` message, we can open a new Rails console terminal and update that model field to satisfy our `find_by` line and the method will stop retrying as soon as that condition is met.

No Comments

Post A Comment