Rails的ActionController::BadRequest在生产服务器上导致500服务器错误

11
我们有一个土耳其网站,一些旧链接被某些搜索引擎抓取。这些链接似乎格式不正确或无法处理,因此导致 ActionController::BadRequest 错误。在本地机器上使用 development env 会导致返回带有 ActionController::BadRequest 的 Rails 错误页面。
但是在服务器上我们会得到一个 500 server error。这个问题在其他几个页面上进行了讨论,例如这里。但是没有任何解决方案管用。
在两种情况下,我们都希望重定向到一个“未找到页面”的页面。
我已经尝试过在 ApplicationController 中使用 rescue_from ActionController::BadRequestrescue_from ActionController::RoutingError,因为在前面提到的文章中,他们说 BadRequest 会变成 RoutingError
但是它们都没有起作用。
我希望有人遇到了同样的问题并已经解决了它。感谢您提前的回答。
编辑:
一个示例问题的URL是 http://localhost:3000/Di%c5%ef%bf%bd-f%c4%b1r%c3%a7as%c4%b1
终端输出:
ActionController::BadRequest (ActionController::BadRequest):
  actionpack (4.0.0) lib/action_dispatch/routing/route_set.rb:37:in `block in call'
  actionpack (4.0.0) lib/action_dispatch/routing/route_set.rb:33:in `each'
  actionpack (4.0.0) lib/action_dispatch/routing/route_set.rb:33:in `call'
  actionpack (4.0.0) lib/action_dispatch/journey/router.rb:71:in `block in call'
  actionpack (4.0.0) lib/action_dispatch/journey/router.rb:59:in `each'
  actionpack (4.0.0) lib/action_dispatch/journey/router.rb:59:in `call'
  actionpack (4.0.0) lib/action_dispatch/routing/route_set.rb:655:in `call'
  newrelic_rpm (3.6.4.122) lib/new_relic/rack/error_collector.rb:12:in `call'
  newrelic_rpm (3.6.4.122) lib/new_relic/rack/agent_hooks.rb:22:in `call'
  newrelic_rpm (3.6.4.122) lib/new_relic/rack/browser_monitoring.rb:16:in `call'
  newrelic_rpm (3.6.4.122) lib/new_relic/rack/developer_mode.rb:28:in `call'
  rack (1.5.2) lib/rack/etag.rb:23:in `call'
  rack (1.5.2) lib/rack/conditionalget.rb:25:in `call'
  rack (1.5.2) lib/rack/head.rb:11:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/flash.rb:241:in `call'
  rack (1.5.2) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.5.2) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/cookies.rb:486:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.0.0) lib/active_support/callbacks.rb:373:in `_run__4278100521352222029__call__callbacks'
  activesupport (4.0.0) lib/active_support/callbacks.rb:80:in `run_callbacks'
  actionpack (4.0.0) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/reloader.rb:64:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/remote_ip.rb:76:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  rollbar (0.11.7) lib/rollbar/middleware/rails/show_exceptions.rb:19:in `call_with_rollbar'
  actionpack (4.0.0) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.0.0) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.0.0) lib/rails/rack/logger.rb:21:in `block in call'
  activesupport (4.0.0) lib/active_support/tagged_logging.rb:67:in `block in tagged'
  activesupport (4.0.0) lib/active_support/tagged_logging.rb:25:in `tagged'
  activesupport (4.0.0) lib/active_support/tagged_logging.rb:67:in `tagged'
  railties (4.0.0) lib/rails/rack/logger.rb:21:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.0.0) lib/active_support/cache/strategy/local_cache.rb:83:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.0.0) lib/action_dispatch/middleware/static.rb:64:in `call'
  railties (4.0.0) lib/rails/engine.rb:511:in `call'
  railties (4.0.0) lib/rails/application.rb:97:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  puma (2.6.0) lib/puma/server.rb:486:in `handle_request'
  puma (2.6.0) lib/puma/server.rb:357:in `process_client'
  puma (2.6.0) lib/puma/server.rb:250:in `block in run'
  puma (2.6.0) lib/puma/thread_pool.rb:92:in `call'
  puma (2.6.0) lib/puma/thread_pool.rb:92:in `block in spawn_thread'

最好的祝愿


我也遇到了同样的问题。希望能得到答案。 - user1354743
你能展示一下堆栈跟踪吗?此外,这个答案有用吗?https://dev59.com/qX3aa4cB1Zd3GeqPhLgZ#22473964 - dax
我已经将堆栈跟踪添加到问题中,我也尝试过了,但它也没有起作用。 - satanik
你是否正在使用config.exceptions_app?我仍然没有解决:https://github.com/rails/rails/issues/15124 - Lukas Eklund
3个回答

4

我在一个Rails 4.0.x应用程序中遇到了完全相同的问题,它污染了我的New Relic错误页面。

我通过编写一个中间件来解决这个问题,该中间件缓存ActionController :: BadRequest 错误,记录日志并返回400错误页面。(与404错误相比,400错误更为合适。)

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>

这将停止处理rails堆栈,记录错误并向用户返回400.html页面,从而使应用程序可以处理更有效的请求。

我还将400页缓存为实例变量,以节省垃圾回收和磁盘IO。


我很遗憾仍然收到这个错误:在#中发生了ActionController :: BadRequest: ActionController :: BadRequest app / middleware / catch_request_errors.rb:8:in `call' - Pepa Chmel
2
Rails 7:config.middleware.insert_before ActionDispatch::Callbacks,CatchRequestErrors - Daniel

2
我猜测您的某个路由或Rack中间件无效,导致了500错误。在新的Rails应用程序中,URL为http://localhost:3000/Di%c5%ef%bf%bd-f%c4%b1r%c3%a7as%c4%b1时没有不正确的行为-应用程序按预期返回404错误。此外,对http://127.0.0.1:3000/?foo[]=array&foo[hash]=hash的请求会返回正确的400错误响应(BadRequest)。
请尝试像这样重写路由:
Rails.application.routes.draw do
  get '/*path', :to => lambda { |env| [200, {}, [env.to_s]]}
  # omited
end

请查看响应状态 - 如果为200,则问题在Rails应用程序中,否则问题可能在Rack中间件的其他地方。

rails -v #=> Rails 4.1.1


1

有一个黑客技巧。将此代码放置在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

它将响应类似于http://127.0.0.1:3000/?foo[]=array&foo[hash]=hash的请求,返回400。

编辑:

另外,可以实现中间件来检查参数的正确性。

通过中间件捕获错误查询。

# 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

你好,谢谢。但是你能解释一下如何使用这段代码吗?我创建了一个文件./config/initializers/bad_request_hack.rb,并将代码放在那里,当我重新启动服务器时,什么也没有改变。实际上,当我使用你的url示例/?foo[]=array&foo[hash]=hash时,它会显示“未定义的BadRequest方法”。如果我使用我的url/Eskisehir/indirimler/Di%c5%c3%af%c2%bf%c2%bd-f%c4%b1r%c3%a7as%c4%b1,我会得到与之前相同的错误。 - satanik
我的错误已经被修复,修正后的代码为:raise ActionController::BadRequest.new("asd", e) - Zhomart
现在针对您的URL,我收到了Invalid asd parameters: expected Hash (got Array) for param 'foo'的错误信息,而我的URL是相同的。请问“asd”是什么意思? - satanik
谢谢您对您的URL的良好工作,但是我呈现的那个仍然会引发错误请求。 - satanik
添加了使用中间件的示例,这应该会有所帮助。 - Zhomart
显示剩余14条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接