Skip to content
This repository has been archived by the owner on Jan 13, 2022. It is now read-only.

Handle HTTP 400 HTML contained response as empty JSON #185

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
11 changes: 10 additions & 1 deletion lib/faraday/raise_http_exception.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,16 @@ def error_body(body)
# body gets passed as a string, not sure if it is passed as something else from other spots?
if not body.nil? and not body.empty? and body.kind_of?(String)
# removed multi_json thanks to wesnolte's commit
body = ::JSON.parse(body)
body = begin
::JSON.parse(body)
rescue JSON::ParserError => e
# handle HTML response here as empty JSON
if e.message.match /unexpected token/
nil
else
raise e
end
end
end

if body.nil?
Expand Down
14 changes: 14 additions & 0 deletions spec/faraday/response_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,20 @@
end
end

context "when a 400 is raised with an HTML response" do
before do
stub_get('users/self/feed.json').to_return(
:body => '<html><body><h1>400 Bad Request</h1> The server returned an invalid or incomplete response. </body></html>',
:status => 400)
end

it "should return the body error type" do
expect do
@client.user_media_feed()
end.to raise_error(Instagram::BadRequest)
end
end

context 'when a 502 is raised with an HTML response' do
before do
stub_get('users/self/feed.json').to_return(
Expand Down