Skip to content

Commit

Permalink
Raise exception on nil status
Browse files Browse the repository at this point in the history
  • Loading branch information
jonnyom committed Sep 30, 2019
1 parent dcae077 commit 276b069
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/faraday/error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@ def initialize(exc, response = nil)
super(exc.message)
@wrapped_exception = exc
elsif exc.respond_to?(:each_key)
super("the server responded with status #{exc[:status]}")
nil_status_message = 'the server responded with a nil status'
status_exists_msg = "the server responded with status #{exc[:status]}"
message = exc[:status].nil? ? nil_status_message : status_exists_msg
super(message)
@response = exc
else
super(exc.to_s)
Expand Down Expand Up @@ -69,6 +72,10 @@ class ConflictError < ClientError
class UnprocessableEntityError < ClientError
end

# Raised by Faraday::Response::RaiseError in case of a nil status in response.
class NilStatusError < ClientError
end

# Faraday server error class. Represents 5xx status responses.
class ServerError < Error
end
Expand Down
2 changes: 2 additions & 0 deletions lib/faraday/response/raise_error.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ def on_complete(env)
raise Faraday::ConflictError, response_values(env)
when 422
raise Faraday::UnprocessableEntityError, response_values(env)
when nil
raise Faraday::NilStatusError, response_values(env)
when ClientErrorStatuses
raise Faraday::ClientError, response_values(env)
when ServerErrorStatuses
Expand Down
8 changes: 8 additions & 0 deletions spec/faraday/response/raise_error_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
stub.get('conflict') { [409, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('unprocessable-entity') { [422, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('4xx') { [499, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('nil-status') { [nil, { 'X-Reason' => 'because' }, 'keep looking'] }
stub.get('server-error') { [500, { 'X-Error' => 'bailout' }, 'fail'] }
end
end
Expand Down Expand Up @@ -72,6 +73,13 @@
end
end

it 'raises Faraday::NilStatusError for nil status in response' do
expect { conn.get('nil-status') }.to raise_error(Faraday::NilStatusError) do |ex|
expect(ex.message).to eq('the server responded with a nil status')
expect(ex.response[:headers]['X-Reason']).to eq('because')
end
end

it 'raises Faraday::ClientError for other 4xx responses' do
expect { conn.get('4xx') }.to raise_error(Faraday::ClientError) do |ex|
expect(ex.message).to eq('the server responded with status 499')
Expand Down

0 comments on commit 276b069

Please sign in to comment.