Rails ActionController::BadRequest causes 500 Server Error on production server

喜你入骨 提交于 2019-12-05 02:35:18

I had the exact same issue in a Rails 4.0.x app where it was polluting my New Relic error page.

I got around this by writing a middleware that caches the ActionController::BadRequest error, Logs it and returns a 400 error page. (A 400 seemed more appropriate then a 404 error.)

app/middleware/catch_request_errors.rb

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

  def call(env)
    begin
      @app.call(env)
    rescue ActionController::BadRequest => error
      ::Rails.logger.warn("WARN: 400 ActionController::BadRequest: #{env['REQUEST_URI']}")
      @html_400_page ||= File.read(::Rails.root.join('public', '400.html'))
      [
          400, { "Content-Type" => "text/html" },
          [ @html_400_page ]
      ]
    end
  end
end

config/application.rb

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

public/400.html

<!DOCTYPE html>
<html>
<head>
  <title>Your request could not be handled (400)</title>
  <style type="text/css">
    body { background-color: #fff; color: #666; text-align: center; font-family: arial, sans-serif; }
    div.dialog {
      width: 25em;
      padding: 0 4em;
      margin: 4em auto 0 auto;
      border: 1px solid #ccc;
      border-right-color: #999;
      border-bottom-color: #999;
    }
    h1 { font-size: 100%; color: #f00; line-height: 1.5em; }
  </style>
</head>

<body>
  <!-- This file lives in public/400.html -->
  <div class="dialog">
    <h1>Your request could not be handled.</h1>
    <p>Please check the url and post data for syntax errors.</p>
  </div>
</body>
</html>

This stops processing the rails stack, logs the error and returns the 400.html page to the user freeing the app to process a more valid request.

I'm also caching the 400 page as a instance variable to save on GC and Disc IO.

There is a hack. Put this code inside initializers

module Rack
  module Utils
    alias_method :original_normalize_params, :normalize_params
    module_function :original_normalize_params

    def normalize_params(params, name, v = nil)
      begin
        original_normalize_params(params, name, v)
      rescue => e
        raise ActionController::BadRequest.new("Incorrect URL")
      end
    end

    module_function :normalize_params
  end
end

It will respond with 400 for requests like http://127.0.0.1:3000/?foo[]=array&foo[hash]=hash

EDIT:

Also, it is possible to implement middleware which checks for correctness of parameters.

Catching bad queries by middleware

# config/application.rb

require File.expand_path('../../lib/query_validator', __FILE__)

module MyApp
  class Application < Rails::Application
    # configurations

    config.middleware.insert_before('ActionDispatch::ShowExceptions', QueryValidator)
  end
end

# lib/query_validator.rb

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

  def call(env)
    begin
      Rack::Utils.parse_nested_query(env['QUERY_STRING'])

      env['QUERY_STRING'].valid_encoding? or
        raise ActionController::BadRequest, "Invalid parameter: #{env['QUERY_STRING']}"
    rescue => e
      env['QUERY_STRING'] = ''
      env['my_app.query_errors'] = 'Invalid query.'
    end

    @app.call(env)
  end
end


# application_controller.rb
class ApplicationController < ActionController::Base
  before_filter do
    if env['my_app.query_errors']
      flash[:alert] = env['my_app.query_errors']
      redirect_to root_path
    end
  end

end
Semjon

I suppose that one of your routes or Rack middleware is invalid and causes the 500 error. In new Rails app there is no incorrect behaviour with url http://localhost:3000/Di%c5%ef%bf%bd-f%c4%b1r%c3%a7as%c4%b1 - app returns a 404 error as expected. Also request to http://127.0.0.1:3000/?foo[]=array&foo[hash]=hash return absolutely correct response with 400 error (BadRequest).

Try to rewrite routes like this:

Rails.application.routes.draw do
  get '/*path', :to => lambda { |env| [200, {}, [env.to_s]]}
  # omited
end

and take a look to response status - if it 200, than problem in your Rails application, otherwise anywhere else in the rack middleware.

rails -v #=> Rails 4.1.1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!