Skip to content

Commit 095edc9

Browse files
authored
Merge pull request #181 from Juanmcuello/json-body-parser-fix
Rack::JSONBodyParser. Do not rescue JSON:ParserError
2 parents 0a2e085 + ecc8a47 commit 095edc9

File tree

2 files changed

+15
-7
lines changed

2 files changed

+15
-7
lines changed

lib/rack/contrib/json_body_parser.rb

+9-7
Original file line numberDiff line numberDiff line change
@@ -55,16 +55,18 @@ def initialize(
5555
end
5656

5757
def call(env)
58-
if @verbs.include?(env[Rack::REQUEST_METHOD]) &&
59-
@matcher.call(@media, env['CONTENT_TYPE'])
58+
begin
59+
if @verbs.include?(env[Rack::REQUEST_METHOD]) &&
60+
@matcher.call(@media, env['CONTENT_TYPE'])
6061

61-
update_form_hash_with_json_body(env)
62+
update_form_hash_with_json_body(env)
63+
end
64+
rescue JSON::ParserError
65+
body = { error: 'Failed to parse body as JSON' }.to_json
66+
header = { 'Content-Type' => 'application/json' }
67+
return Rack::Response.new(body, 400, header).finish
6268
end
6369
@app.call(env)
64-
rescue JSON::ParserError
65-
body = { error: 'Failed to parse body as JSON' }.to_json
66-
header = { 'Content-Type' => 'application/json' }
67-
Rack::Response.new(body, 400, header).finish
6870
end
6971

7072
private

test/spec_rack_json_body_parser_spec.rb

+6
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,12 @@ def create_parser(app, **args, &block)
6666
_(result).must_be_empty
6767
end
6868

69+
specify "should not rescue JSON:ParserError raised by the app" do
70+
env = mock_env
71+
app = ->(env) { raise JSON::ParserError }
72+
_( -> { create_parser(app).call(env) }).must_raise JSON::ParserError
73+
end
74+
6975
describe "contradiction between body and type" do
7076
specify "should return bad request with a JSON-encoded error message" do
7177
env = mock_env(input: 'This is not JSON')

0 commit comments

Comments
 (0)