Rescue from MultiJson::DecodeError in Ruby on Rails

If you are developing an API with Rails you need to rescue from the errors produced by a bad formatted JSON. In order to do that I use a middleware file placed in app/middleware/ named ParamsParserRescue.rb.

class ParamsParserRescue < ActionDispatch::ParamsParser
  def call(env)
    begin
      super(env)
    rescue MultiJson::DecodeError
      [400, {}, ["Bad Request"]]
    end
  end
end

And with this middleware file you need to tell Rails that should use it. In the configuration file application.rb add:

config.middleware.swap ActionDispatch::ParamsParser, "ParamsParserRescue"

Basically, we are doing whatever the call method does in ActionDispatch::ParamsParser (which is not much) and if the MultiJson::DecodeError exception is raised then we return a 400 HTTP Code instead of crashing.