Skip to content

Commit

Permalink
Rack::JSONBodyParser: rescue all parser exceptions
Browse files Browse the repository at this point in the history
Rescue all exceptions raised by the parser as long as it is StandardError
subclass (which should be all the exceptions raised by different libraries).

This is specially needed when using a parser other than JSON. Otherwise we need
to rescue the corresponding exception and raise JSON:ParseError inside the
block.
  • Loading branch information
Juan Manuel Cuello committed Jun 20, 2023
1 parent 095edc9 commit 830c578
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
13 changes: 11 additions & 2 deletions lib/rack/contrib/json_body_parser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def call(env)

update_form_hash_with_json_body(env)
end
rescue JSON::ParserError
rescue ParserError
body = { error: 'Failed to parse body as JSON' }.to_json
header = { 'Content-Type' => 'application/json' }
return Rack::Response.new(body, 400, header).finish
Expand All @@ -71,13 +71,22 @@ def call(env)

private

class ParserError < StandardError; end

def update_form_hash_with_json_body(env)
body = env[Rack::RACK_INPUT]
return unless (body_content = body.read) && !body_content.empty?

body.rewind # somebody might try to read this stream

begin
parsed_body = @parser.call(body_content)
rescue StandardError
raise ParserError
end

env.update(
Rack::RACK_REQUEST_FORM_HASH => @parser.call(body_content),
Rack::RACK_REQUEST_FORM_HASH => parsed_body,
Rack::RACK_REQUEST_FORM_INPUT => body
)
end
Expand Down
11 changes: 11 additions & 0 deletions test/spec_rack_json_body_parser_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@ def create_parser(app, **args, &block)
_( -> { create_parser(app).call(env) }).must_raise JSON::ParserError
end

specify "should rescue StandardError subclasses raised by the parser" do
class CustomParserError < StandardError; end

parser = create_parser(app) do |_body|
raise CustomParserError.new
end

res = parser.call(mock_env)
_(res[0]).must_equal 400
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 830c578

Please sign in to comment.