Skip to content

Commit

Permalink
Add a simple retry
Browse files Browse the repository at this point in the history
Handle the case when the YouTube API raises a backend 500 error randomly
  • Loading branch information
treble37 committed Jun 17, 2017
1 parent 38c6892 commit 2d5a8e5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
14 changes: 13 additions & 1 deletion lib/yt/http_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,24 @@ def run
parse_response!
end
else
raise Yt::HTTPError, error_message
retry_run
end
end

private

# retry the run method in case of a random 500 error from YouTube API
def retry_run
if @retried
raise Yt::HTTPError, error_message
else
@retried = true
@response = nil
sleep 5
run
end
end

# @return [URI::HTTPS] the (memoized) URI of the request.
def uri
attributes = {host: @host, path: @path, query: URI.encode_www_form(query)}
Expand Down
15 changes: 15 additions & 0 deletions spec/http_request_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,19 @@
expect{request.run}.to raise_error Yt::ConnectionError
end
end

context 'given that YouTube API raises an error' do
context 'only once' do
path = '/discovery/v1/apis/youtube/v3/rest'
headers = {'User-Agent' => 'Yt::HTTPRequest'}
params = {verbose: 1}
let(:request) { Yt::HTTPRequest.new path: path, headers: headers, params: params }
let(:retry_response) { Net::HTTPSuccess.new '1.0', '200', 'OK' }
before { expect(Net::HTTP).to receive(:start).at_least(:once).and_return retry_response }
it 'returns the HTTP response with the JSON-parsed body' do
allow(retry_response).to receive(:body).and_return('{"fake": "body"}')
expect { request.run }.not_to raise_error
end
end
end
end

0 comments on commit 2d5a8e5

Please sign in to comment.