【问题标题】:How to properly render custom 404 and 500 pages?如何正确呈现自定义 404 和 500 页面?
【发布时间】:2012-02-11 11:22:16
【问题描述】:

有没有办法告诉 Rails 呈现您的自定义错误页面(例如,您在 ErrorsController 中写的错误页面)?我搜索了很多主题,其中一个似乎有点工作的主题是添加到您的ApplicationController 类似

if Rails.env.production?
  rescue_from Exception, :with => :render_error
  rescue_from ActiveRecord::RecordNotFound, :with => :render_not_found
  rescue_from ActionController::UnknownController, :with => :render_not_found
  rescue_from ActionController::UnknownAction, :with => :render_not_found
end

然后你以你想要的方式编写你的方法render_errorrender_not_found。在我看来,这似乎是一个非常不雅的解决方案。此外,这很糟糕,因为您必须确切知道可能发生的所有错误。这是一个临时解决方案。

另外,用这种方式拯救ActionController::RoutingError 真的不容易。我看到一种方法是添加类似

get "*not_found", :to => "errors#not_found"

到您的routes.rb。但是,如果您想手动在某处提出ActionController::RoutingError 怎么办?例如,如果一个不是管理员的人试图通过猜测 URL 来访问“管理”控制器。在这些情况下,我更喜欢引发 404,而不是引发某种“未经授权的访问”错误,因为这实际上会告诉人们他猜到了 URL。如果你手动提升它,它会尝试渲染一个 500 的页面,我想要一个 404。

那么有没有办法告诉 Rails:“在所有情况下,您通常会渲染 404.html500.html,渲染我的自定义 404 和 500 页面”? (当然,我从public文件夹中删除了404.html500.html页面。)

【问题讨论】:

    标签: ruby-on-rails http-status-code-404 http-error


    【解决方案1】:

    不幸的是,我知道没有任何方法可以被覆盖以提供您想要的东西。您可以使用环绕过滤器。您的代码将如下所示:

    class ApplicationController < ActionController::Base
      around_filter :catch_exceptions
    
      protected
        def catch_exceptions
          yield
        rescue => exception
          if exception.is_a?(ActiveRecord::RecordNotFound)
            render_page_not_found
          else
            render_error
          end
        end
    end
    

    您可以按照您认为适合该方法的方式处理每个错误。那么您的 #render_page_not_found#render_error 方法必须类似于

    render :template => 'errors/404'
    

    你需要在app/views/errors/404.html.[haml|erb]有一个文件

    【讨论】:

    • 哇,这真是太棒了。这样我只需要知道哪些是“404异常”,这很容易。很好的解决方案:)。一个问题,在您看来,处理未经授权的访问的最佳方法是什么?提高ActionController::RoutingError 对我来说实际上并不合适。
    • 该死,我不能投票,因为我还没有 15 点声望。
    • 我一直使用head :unauthorized。它易于阅读和意图揭示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-28
    • 1970-01-01
    • 2019-12-27
    • 2013-02-04
    • 2013-07-13
    • 2019-01-24
    相关资源
    最近更新 更多