Permalink
Browse files

Merge branch 'feature-avoid-failure-on-bad-json' of https://github.co…

…m/shingara/faraday into shingara-feature-avoid-failure-on-bad-json
  • Loading branch information...
2 parents 61de2b9 + c342bd9 commit fbf25361686e25b465030af3562035c270430e15 @technoweenie technoweenie committed Oct 5, 2010
View
@@ -3,5 +3,6 @@ module Error
class ClientError < StandardError; end
class ConnectionFailed < ClientError; end
class ResourceNotFound < ClientError; end
+ class ParsingError < ClientError; end
end
end
@@ -8,16 +8,24 @@ class Response::ActiveSupportJson < Response::Middleware
def self.register_on_complete(env)
env[:response].on_complete do |finished_env|
- finished_env[:body] = ActiveSupport::JSON.decode(finished_env[:body])
+ finished_env[:body] = parse(finished_env[:body])
+
end
end
rescue LoadError, NameError => e
self.load_error = e
end
-
+
def initialize(app)
super
@parser = nil
end
+
+ def self.parse(body)
+ ActiveSupport::JSON.decode(body)
+ # TODO: Maybe rescue Exception can be better ...
+ rescue Yajl::ParseError => e
+ raise Faraday::Error::ParsingError
+ end
end
end
@@ -5,16 +5,22 @@ class Response::Yajl < Response::Middleware
def self.register_on_complete(env)
env[:response].on_complete do |finished_env|
- finished_env[:body] = Yajl::Parser.parse(finished_env[:body])
+ finished_env[:body] = parse(finished_env[:body])
end
end
rescue LoadError, NameError => e
self.load_error = e
end
-
+
def initialize(app)
super
@parser = nil
end
+
+ def self.parse(body)
+ Yajl::Parser.parse(body)
+ rescue Yajl::ParseError => e
+ raise Faraday::Error::ParsingError
+ end
end
end
@@ -4,7 +4,7 @@ class ResponseMiddlewareTest < Faraday::TestCase
[:yajl, :rails_json].each do |key|
encoder = Faraday::Response.lookup_module(key)
next if !encoder.loaded?
-
+
define_method "test_uses_#{key}_to_parse_json_content" do
response = create_json_connection(encoder).get('json')
assert response.success?
@@ -22,6 +22,12 @@ class ResponseMiddlewareTest < Faraday::TestCase
assert response.success?
assert !response.body
end
+
+ define_method "test_use_#{key}_to_raise_Faraday_Error_Parsing_with_no_json_content" do
+ assert_raises Faraday::Error::ParsingError do
+ response = create_json_connection(encoder).get('bad_json')
+ end
+ end
end
def create_json_connection(encoder)
@@ -30,6 +36,7 @@ def create_json_connection(encoder)
stub.get('json') { [200, {'Content-Type' => 'text/html'}, "[1,2,3]"] }
stub.get('blank') { [200, {'Content-Type' => 'text/html'}, ''] }
stub.get('nil') { [200, {'Content-Type' => 'text/html'}, nil] }
+ stub.get("bad_json") {[200, {'Content-Type' => 'text/html'}, '<body></body>']}
end
b.use encoder
end

0 comments on commit fbf2536

Please sign in to comment.