How to avoid rails from crashing on the wrong content type

I am using rails 3.2.8 on Ubuntu 12.04

I am creating a json only webservice. Now if someone sends me data that is not json, but sets the content type to application / json, the rails app throws an exception and returns 500 (internal server error).

This exception happens in rails before the controller action is called as rails tries to create a params structure and parse the incoming data as JSON.

I'm not sure if this is the correct behavior. I would prefer if this would get rid of the exception and tell me in some kind of custom handler or in my action with some set of variables. I would like to specify 415 (unsupported media type) or 422 (raw object). I guess 422 is more appropriate in this case.

Any ideas on how this can be done?

+3


source to share


1 answer


Let's say you need to modify your middleware a little. Create your own middleware and insert it before ParamsParser

or override ParamsParser

.

Take a look at this one, there is a sample override ParamsParser

.



Creating a custom middlevare has another benefit: if the data json

is but the content type is not application/json

, you can fix it here ( example ).

+1


source







All Articles