From a68b8cb758001f309f09d3220c367ba3ebd41938 Mon Sep 17 00:00:00 2001 From: Steve Bazyl Date: Mon, 19 Sep 2016 14:16:36 -0700 Subject: [PATCH] #467 - Restore error handling for failed downloads --- lib/google/apis/core/download.rb | 9 +++++++-- spec/google/apis/core/download_spec.rb | 11 +++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/google/apis/core/download.rb b/lib/google/apis/core/download.rb index db55509a7..05de2ea3f 100644 --- a/lib/google/apis/core/download.rb +++ b/lib/google/apis/core/download.rb @@ -23,6 +23,7 @@ module Google # Streaming/resumable media download support class DownloadCommand < ApiCommand RANGE_HEADER = 'range' + OK_STATUS = [200, 201, 206] # File or IO to write content to # @return [String, File, #write] @@ -65,7 +66,7 @@ module Google # @raise [Google::Apis::ClientError] The request is invalid and should not be retried without modification # @raise [Google::Apis::AuthorizationError] Authorization is required def execute_once(client, &block) - client.get(@download_url || url) do |req| + response = client.get(@download_url || url) do |req| apply_request_options(req) check_if_rewind_needed = false if @offset > 0 @@ -73,7 +74,7 @@ module Google req.header[RANGE_HEADER] = sprintf('bytes=%d-', @offset) check_if_rewind_needed = true end - req.on_body(200, 201, 206) do |res, chunk| + req.on_body(*OK_STATUS) do |res, chunk| check_status(res.status_code, chunk) unless res.status_code.nil? if check_if_rewind_needed && res.status_code != 206 # Oh no! Requested a chunk, but received the entire content @@ -88,6 +89,10 @@ module Google @download_io.flush end end + + # Since the on_body block only runs on success, check status again just in case it failed + check_status(response.status_code, response.body) unless OK_STATUS.include?(response.status_code.to_i) + if @close_io_on_finish result = nil else diff --git a/spec/google/apis/core/download_spec.rb b/spec/google/apis/core/download_spec.rb index 9f56beb0f..135b47457 100644 --- a/spec/google/apis/core/download_spec.rb +++ b/spec/google/apis/core/download_spec.rb @@ -48,6 +48,17 @@ RSpec.describe Google::Apis::Core::DownloadCommand do end end + context 'with error' do + before(:example) do + stub_request(:get, 'https://www.googleapis.com/zoo/animals') + .to_return(status: [404, 'Not Found'], body: '') + end + + it 'should raise error' do + expect {received}.to raise_error(Google::Apis::ClientError) + end + end + context 'with disconnects' do before(:example) do stub_request(:get, 'https://www.googleapis.com/zoo/animals')