Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions lib/http/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,13 @@ def initialize(response)
end
end

# Raised when `Response#parse` fails due to any underlying reason (unexpected
# MIME type, or decoder fails). See `Exception#cause` for the original exception.
class ParseError < ResponseError; end

# Requested MimeType adapter not found.
class UnsupportedMimeTypeError < Error; end

# Generic Timeout error
class TimeoutError < Error; end

Expand Down
4 changes: 3 additions & 1 deletion lib/http/mime_type.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require "http/errors"

module HTTP
# MIME type encode/decode adapters
module MimeType
Expand Down Expand Up @@ -35,7 +37,7 @@ def register_adapter(type, adapter)
# @raise [Error] if no adapter found
# @return [Class]
def [](type)
adapters[normalize type] || raise(Error, "Unknown MIME type: #{type}")
adapters[normalize type] || raise(UnsupportedMimeTypeError, "Unknown MIME type: #{type}")
end

# Register a shortcut for MIME type
Expand Down
3 changes: 3 additions & 0 deletions lib/http/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

require "forwardable"

require "http/errors"
require "http/headers"
require "http/content_type"
require "http/mime_type"
Expand Down Expand Up @@ -155,6 +156,8 @@ def chunked?
# @return [Object]
def parse(type = nil)
MimeType[type || mime_type].decode to_s
rescue => e
raise ParseError, e.message
end

# Inspect a response
Expand Down
13 changes: 11 additions & 2 deletions spec/lib/http/response_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,8 @@
context "with unknown content type" do
let(:content_type) { "application/deadbeef" }

it "raises HTTP::Error" do
expect { response.parse }.to raise_error HTTP::Error
it "raises HTTP::ParseError" do
expect { response.parse }.to raise_error HTTP::ParseError
end
end

Expand All @@ -125,6 +125,15 @@
expect(response.parse(:json)).to eq "foo" => "bar"
end
end

context "when underlying parser fails" do
let(:content_type) { "application/deadbeef" }
let(:body) { "" }

it "raises HTTP::ParseError" do
expect { response.parse }.to raise_error HTTP::ParseError
end
end
end

describe "#flush" do
Expand Down
Loading