Skip to content

Instantly share code, notes, and snippets.

@joaovictor-local
Created May 5, 2022 14:07
Show Gist options
  • Save joaovictor-local/5d0b60451e79101437410434fa12c7bd to your computer and use it in GitHub Desktop.
Save joaovictor-local/5d0b60451e79101437410434fa12c7bd to your computer and use it in GitHub Desktop.
retry on known error # ruby
module Error
module ErrorHandler
def retry_on_known_error(retry_limit:, known_errors: [], &block)
retry_count = 0
block.call
rescue *known_errors => e
raise e if retry_count == retry_limit
retry_count += 1
retry
end
module_function :retry_on_known_error
end
end
# frozen_string_literal: true
require 'rails_helper'
class TestError < StandardError
end
class RetryMock
attr_reader :retry_count
def initialize
@retry_count = 0
end
def try
@retry_count += 1
raise TestError if @retry_count != 3
end
end
RSpec.describe Error::ErrorHandler do
describe '#retry_on_known_error' do
context 'when is raised a unknowed error' do
it "don't retry" do
expect do
subject.retry_on_known_error(retry_limit: 3, known_errors: []) do
raise TestError
end
end.to raise_error(TestError)
end
end
context 'when is raised a knowed error' do
it 'retry until retry limit' do
retry_mock = RetryMock.new
subject.retry_on_known_error(retry_limit: 3, known_errors: [TestError]) do
retry_mock.try
end
expect(retry_mock.retry_count).to eq(3)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment