From ecc8a47764166cb401c1eb14df423e550d3d8743 Mon Sep 17 00:00:00 2001 From: "Juan M. Cuello" Date: Fri, 23 Oct 2020 21:19:47 -0300 Subject: [PATCH] Rack::JSONBodyParser. Do not rescue JSON:ParserError Do not rescue JSON:ParserError if it was raised inside de app. --- lib/rack/contrib/json_body_parser.rb | 16 +++++++++------- test/spec_rack_json_body_parser_spec.rb | 6 ++++++ 2 files changed, 15 insertions(+), 7 deletions(-) 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')