1

有没有办法告诉 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:“在所有情况下,您通常会渲染 a404.html或 a 500.html,渲染我的自定义 404 和 500 页面”?(当然,我从文件夹中删除了404.html500.html页面public。)

4

1 回答 1

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]

于 2012-02-11T17:28:13.373 回答