【问题标题】:How can I show 404 error page instead of routing error?如何显示 404 错误页面而不是路由错误?
【发布时间】:2011-09-13 10:49:57
【问题描述】:

在我的 Ruby on Rails 应用程序中,当给定路由与我的应用程序不匹配或不存在时,我想显示 404 错误页面而不是路由错误。有人可以帮我实现吗?

【问题讨论】:

    标签: ruby-on-rails routing


    【解决方案1】:

    这已经是生产中的默认行为。在开发环境中显示路由错误,让开发人员注意到并修复它们。

    如果你想尝试,请在生产模式下启动服务器并检查它。

    $ script/rails s -e production
    

    【讨论】:

      【解决方案2】:

      如果您无法轻松地在本地运行生产模式,请在您的 config/environments/development.rb 文件中将 consider_all_requests_local 设置为 false。

      【讨论】:

        【解决方案3】:

        ApplicationController

         rescue_from ActiveRecord::RecordNotFound, :with => :rescue404
         rescue_from ActionController::RoutingError, :with => :rescue404
        
          def rescue404
            #your custom method for errors, you can render anything you want there
          end
        

        【讨论】:

          【解决方案4】:

          这会返回404页面

          在应用程序控制器中

          class ApplicationController < ActionController::Base
          
                rescue_from ActiveRecord::RecordNotFound,    with: :route_not_found
                rescue_from ActionController::RoutingError,  with: :route_not_found
                rescue_from ActionController::UnknownFormat, with: :route_not_found
          
          
              def route_not_found
                  render file: Rails.public_path.join('404.html'), status: :not_found, layout: false
                end
          

          【讨论】:

            【解决方案5】:

            您可以捕获在找不到路由时引发的异常,然后呈现自定义页面。如果您需要有关代码的帮助,请告诉我。可能有很多其他方法可以做到这一点,但这绝对有效。

            【讨论】:

              猜你喜欢
              • 2019-03-17
              • 1970-01-01
              • 2013-01-09
              • 1970-01-01
              • 2016-10-20
              • 2014-06-24
              • 2020-01-21
              • 2023-03-12
              • 2013-08-31
              相关资源
              最近更新 更多