Wednesday, April 1, 2020

Retry ruby code with exceptions multiple times

This problem I faced is pretty simple. A method calling an external API or resource which might throw a random error or fail intermittently. So I want to simple retry because this error is ignorable if it happens one or two times.

Now the standard ruby's retry and redo keywords are not helping here. Because the retry will keep retrying endlessly and I want to raise the error after a few retries, and the redo requires a flag to make it stop. So my solution to retry my ruby code for a few times if a specific exception happens was as simple as a method with the retry logic and accepting a block to keep my code cleaner. And whenever I need to retry a not-so-reliable API, I wrap my code in this method as a block and choose the exception to retry when it happens and how many times to retry.

# whatever method I am using
def do_something_with_tolerance_to_errors
  response = with_error_retry(WhateverException, 2) do
    # my code goes here

# my retry handler
def with_error_retry(error_class, retries_count)
rescue error_class => e
  @retries ||= 0
  raise e if @retries >= retries_count

  @retries += 1

No comments:

Post a Comment