Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rack::JSONBodyParser: support passing the parser error class #184

Merged
merged 2 commits into from
Oct 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 if body.respond_to?(: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 @@ -64,6 +64,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