How to prevent error filtering the request via Rack Middleware

305 Views Asked by At

Hi I am having an issue in my current project, often we are receiving an error, Current application is running on Rails2.3.5 and Ruby 1.8.7

(ActionController::MethodNotAllowed) "Only getrequests are allowed."

For that I have found few options like

  • prevent the error blocking non GET/POST/HEAD requests using your webserver
  • prevent the error filtering the request via Rack Middleware

So would like to know how to prevent it via Rack Middleware.

Please some one suggest/assist me to get rid of this problem.

TIA.

1

There are 1 best solutions below

0
Sanjay Prajapati On

You would need to create custom middleware and insert it before or after as per the requirement in application.rb.

I would need to handle json parse error in one of the projects and I have created the middle ware as below:

class CatchJsonParseErrors
  def initialize(app)
    @app = app
  end

  def call(env)
    begin
      @app.call(env)
    rescue ActionDispatch::ParamsParser::ParseError => error
      if env['HTTP_ACCEPT'] =~ /application\/json/
        error_output = "There was a problem in the JSON: #{error}"
        return [
          400, { "Content-Type" => "application/json" },
          [ { status: 400, error: error_output }.to_json ]
        ]
      else
        raise error
      end
    end
  end
end

And added below line in application.rb file :

config.middleware.insert_before ActionDispatch::ParamsParser, "CatchJsonParseErrors"