Skip to content

Commit

Permalink
Merge pull request #181 from Juanmcuello/json-body-parser-fix
Browse files Browse the repository at this point in the history
Rack::JSONBodyParser. Do not rescue JSON:ParserError
  • Loading branch information
andrykonchin committed Oct 24, 2020
2 parents 0a2e085 + ecc8a47 commit 095edc9
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
16 changes: 9 additions & 7 deletions lib/rack/contrib/json_body_parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions test/spec_rack_json_body_parser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down

0 comments on commit 095edc9

Please sign in to comment.