diff --git a/lib/rack/contrib/json_body_parser.rb b/lib/rack/contrib/json_body_parser.rb index e979d464..77023a2b 100644 --- a/lib/rack/contrib/json_body_parser.rb +++ b/lib/rack/contrib/json_body_parser.rb @@ -55,16 +55,18 @@ def initialize( end def call(env) - if @verbs.include?(env[Rack::REQUEST_METHOD]) && - @matcher.call(@media, env['CONTENT_TYPE']) + begin + if @verbs.include?(env[Rack::REQUEST_METHOD]) && + @matcher.call(@media, env['CONTENT_TYPE']) - update_form_hash_with_json_body(env) + update_form_hash_with_json_body(env) + end + rescue JSON::ParserError + body = { error: 'Failed to parse body as JSON' }.to_json + header = { 'Content-Type' => 'application/json' } + return Rack::Response.new(body, 400, header).finish end @app.call(env) - rescue JSON::ParserError - body = { error: 'Failed to parse body as JSON' }.to_json - header = { 'Content-Type' => 'application/json' } - Rack::Response.new(body, 400, header).finish end private diff --git a/test/spec_rack_json_body_parser_spec.rb b/test/spec_rack_json_body_parser_spec.rb index 89f93c83..665e7e08 100644 --- a/test/spec_rack_json_body_parser_spec.rb +++ b/test/spec_rack_json_body_parser_spec.rb @@ -66,6 +66,12 @@ def create_parser(app, **args, &block) _(result).must_be_empty end + specify "should not rescue JSON:ParserError raised by the app" do + env = mock_env + app = ->(env) { raise JSON::ParserError } + _( -> { create_parser(app).call(env) }).must_raise JSON::ParserError + end + describe "contradiction between body and type" do specify "should return bad request with a JSON-encoded error message" do env = mock_env(input: 'This is not JSON')