Skip to content

Commit

Permalink
googleapis#467 - Restore error handling for failed downloads
Browse files Browse the repository at this point in the history
  • Loading branch information
sqrrrl committed Sep 19, 2016
1 parent e13da8e commit a68b8cb
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
9 changes: 7 additions & 2 deletions lib/google/apis/core/download.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ module Core
# 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]
Expand Down Expand Up @@ -65,15 +66,15 @@ def release!
# @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
logger.debug { sprintf('Resuming download from offset %d', @offset) }
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
Expand All @@ -88,6 +89,10 @@ def execute_once(client, &block)
@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
Expand Down
11 changes: 11 additions & 0 deletions spec/google/apis/core/download_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,17 @@
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')
Expand Down

0 comments on commit a68b8cb

Please sign in to comment.