First:
I'm using grape for building my API (Rails 4). When someone is sending an invalid JSON body (e.g. forgot the last }
), the following error is raised:
ActionDispatch::ParamsParser::ParseError (795: unexpected token at '{"foobar": 1234
')
I tried it with grapes rescue_from :all
option, but this doesn't work. Inside the stacktrace, I don't see the grape gem involved. It seems that this error is thrown from actionpack:
.gems/gems/actionpack-4.1.4/lib/action_dispatch/middleware/params_parser.rb:53:in `rescue in parse_formatted_parameters'
.gems/gems/actionpack-4.1.4/lib/action_dispatch/middleware/params_parser.rb:32:in `parse_formatted_parameters'
.gems/gems/actionpack-4.1.4/lib/action_dispatch/middleware/params_parser.rb:23:in `call'
But what would be the best way to catch those errors, return a 400: Bad Request
errors, and include the unexpected token at '{"foobar": 1234
message inside the json response?
Second:
I tried to test this with RSpec, but didn't have any luck on sending a raw request with an invalid JSON. I tried it with
post "/my_route", '{some invalid json'
but this doesn't throw the error from above. I thought since Rails 4, the second parameter, passed as a string, is treated like the raw body?