From 0b25c3844e4ca872245598b8e67f53b76be0a0e4 Mon Sep 17 00:00:00 2001 From: Yury Stepanov Date: Fri, 9 Oct 2015 19:30:09 +0800 Subject: [PATCH] Handle HTTP 400 HTML contained response as empty JSON --- lib/faraday/raise_http_exception.rb | 11 ++++++++++- spec/faraday/response_spec.rb | 14 ++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/lib/faraday/raise_http_exception.rb b/lib/faraday/raise_http_exception.rb index ba06a812..b264740f 100644 --- a/lib/faraday/raise_http_exception.rb +++ b/lib/faraday/raise_http_exception.rb @@ -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? diff --git a/spec/faraday/response_spec.rb b/spec/faraday/response_spec.rb index 89f0b1b9..27976d68 100644 --- a/spec/faraday/response_spec.rb +++ b/spec/faraday/response_spec.rb @@ -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 => '

400 Bad Request

The server returned an invalid or incomplete response. ', + :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(