Read more

Use the "retry" keyword to process a piece of Ruby code again.

Ulrich Berkmueller
February 10, 2012Software engineer

Imagine you have a piece of code that tries to send a request to a remote server. Now the server is temporarily not available and raises an exception. In order to re-send the request you could use the following snippet:

def remote_request
  begin
    response = RestClient.get my_request_url
  rescue RestClient::ResourceNotFound => error
    @retries ||= 0
    if @retries < @max_retries
      @retries += 1
      retry
    else
      raise error
    end
  end
  response
end
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

This snippet tries to re-send the request when ResourceNotFound was thrown until @max_retries (termination condition) was reached. With the retry statement you can re-execute the begin block that has been rescued from. Be aware that you could run into an infinite loop without a termination condition.

Posted by Ulrich Berkmueller to makandra dev (2012-02-10 12:19)