Skip to content

Commit 11f7163

Browse files
author
Ted Kulp
committed
Now it doesn't throw a 400 error
Didn't account for regular POST content being in the body on some requests, even if JSON is expected as the result. It now fails gracefully.
1 parent 1958fad commit 11f7163

File tree

2 files changed

+7
-6
lines changed

2 files changed

+7
-6
lines changed

lib/grape/middleware/formatter.rb

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,14 +52,15 @@ def before
5252
fmt = format_from_extension || format_from_header || options[:default_format]
5353

5454
if content_types.key?(fmt)
55-
if !env['rack.input'].nil? and (body = env['rack.input'].read).length != 0
55+
if !env['rack.input'].nil? and (body = env['rack.input'].read).strip.length != 0
5656
parser = parser_for fmt
5757
unless parser.nil?
5858
begin
59-
env['rack.request.form_hash'] = !env['rack.request.form_hash'].nil? ? env['rack.request.form_hash'].merge(parser.call(body)) : parser.call(body)
59+
body = parser.call(body)
60+
env['rack.request.form_hash'] = !env['rack.request.form_hash'].nil? ? env['rack.request.form_hash'].merge(body) : body
6061
env['rack.request.form_input'] = env['rack.input']
6162
rescue
62-
throw :error, :status => 400, :message => 'Body content could not be parsed.'
63+
# It's possible that it's just regular POST content -- just back off
6364
end
6465
end
6566
env['rack.input'].rewind

spec/grape/middleware/formatter_spec.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -130,9 +130,9 @@ def serializable_hash
130130
subject.env['rack.request.form_hash']['is_boolean'].should be_true
131131
subject.env['rack.request.form_hash']['string'].should == 'thing'
132132
end
133-
it 'should be able to fail gracefully if the body is invalid' do
134-
err = catch(:error){ subject.call({'PATH_INFO' => '/info', 'Accept' => 'application/json', 'rack.input' => StringIO.new('{"is_boolean":true,string:"thing"}')}) }
135-
err.should == {:status => 400, :message => "Body content could not be parsed."}
133+
it 'should be able to fail gracefully if the body is regular POST content' do
134+
subject.call({'PATH_INFO' => '/info', 'Accept' => 'application/json', 'rack.input' => StringIO.new('name=Other+Test+Thing')})
135+
subject.env['rack.request.form_hash'].should be_nil
136136
end
137137
end
138138
end

0 commit comments

Comments
 (0)