无效请求:无效的HTTP格式,Rails中的解析失败

时间:2015-03-13 11:51:21

标签: ruby-on-rails ruby http thin

在传递具有特殊字符的字符串时,我收到无效请求:无效的HTTP格式,解析失败错误。日志中的错误如下。

我的要求:

 http://localhost:3000/search/%

错误日志:

 Invalid request: Invalid HTTP format, parsing fails.
/.rvm/gems/ruby-1.9.3-p545/gems/thin-1.6.2/lib/thin/request.rb:84:in `execute'
/.rvm/gems/ruby-1.9.3-p545/gems/thin-1.6.2/lib/thin/request.rb:84:in `parse'
/.rvm/gems/ruby-1.9.3-p545/gems/thin-1.6.2/lib/thin/connection.rb:39:in `receive_data'
/.rvm/gems/ruby-1.9.3-p545/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run_machine'
/.rvm/gems/ruby-1.9.3-p545/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in `run'
/.rvm/gems/ruby-1.9.3-p545/gems/thin-1.6.2/lib/thin/backends/base.rb:73:in `start'
/.rvm/gems/ruby-1.9.3-p545/gems/thin-1.6.2/lib/thin/server.rb:162:in `start'
/.rvm/gems/ruby-1.9.3-p545/gems/rack-1.5.2/lib/rack/handler/thin.rb:16:in `run'
/.rvm/gems/ruby-1.9.3-p545/gems/rack-1.5.2/lib/rack/server.rb:264:in `start'
/.rvm/gems/ruby-1.9.3-p545/gems/railties-4.0.2/lib/rails/commands/server.rb:84:in `start'
/.rvm/gems/ruby-1.9.3-p545/gems/railties-4.0.2/lib/rails/commands.rb:76:in `block in <top (required)>'
/.rvm/gems/ruby-1.9.3-p545/gems/railties-4.0.2/lib/rails/commands.rb:71:in `tap'
/.rvm/gems/ruby-1.9.3-p545/gems/railties-4.0.2/lib/rails/commands.rb:71:in `<top (required)>'
bin/rails:4:in `require'
bin/rails:4:in `<main>'

可能是什么问题?请建议我解决这个问题。

如何在收到以下错误时重定向到另一个页面?

enter image description here

3 个答案:

答案 0 :(得分:1)

%是网址中的特殊字符,用于url-encoding 您应该使用另一个通配符,例如* http://localhost:3000/search/ *

答案 1 :(得分:1)

如下更新您的nginx配置文件,并在公共文件夹中创建400.html文件。

服务器    {       听80;

  root /public;   # <--- be sure to point to 'public'!

error_page 400 /400.html;
location = /400.html {
    internal;
}   

}

答案 2 :(得分:0)

为处理此类错误,会引发许多异常。 比如ActiveRecord::RecordInvalid ActiveRecord::RecordNotFound。但这是模型例外。 使用控制器,我们ActionController::RoutingError ActionController::BadRequest与路由相关,映射网址

因此,当您收到400错误时,它是bad request error,因此您必须通过调用一个方法来处理它,该方法将呈现一个回复的HTML页面

试试这个

class ApplicationController < ActionController::Base
    rescue_from ActionController::RoutingError, :with => :route_not_found_error
    rescue_from ActionController::BadRequest, :with => :bad_request_error
    resue_from StandardError, :with => :render_server_error

    protected
       def route_not_found_error
          render "shared/404", :status => 404
       end

       def bad_request_error
          render "shared/400", :status => 400
       end

       def render_server_error
          render "shared/500", :status => 500
       end
end

在app / views / shared中添加404.html400.html500.html的网页