10

我正在尝试在我的网站中设置自定义错误页面。我正在遵循PerfectLine Blog的指导方针。

它适用于控制器存在但id不存在的情况。例如,我有一个博客控制器并且 id 4 不存在。它显示了自定义错误页面

但在控制器本身不存在的情况下不存在。例如,如果我键入一些带有数字 id 的随机控制器,则不会被我在应用程序控制器中设置的方法捕获以重新路由自定义错误页面。在这种情况下,我得到一个

ActionController::RoutingError (No route matches "/randomcontrollername"):

在终端和rails附带的默认错误页面中。

application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery

  unless Rails.application.config.consider_all_requests_local
    rescue_from Exception,                            :with => :render_error
    rescue_from ActiveRecord::RecordNotFound,         :with => :render_not_found
    rescue_from ActionController::RoutingError,       :with => :render_not_found
    rescue_from ActionController::UnknownController,  :with => :render_not_found
    rescue_from ActionController::UnknownAction,      :with => :render_not_found
  end

  private
  def render_not_found(exception)
     render :template => "/error/404.html.erb", :status => 404
  end

  def render_error(exception)
    render :template => "/error/500.html.erb", :status => 500 
  end

end

请你帮助我好吗。谢谢。

4

2 回答 2

18

您可以使用 rails 中的路线通配符来做到这一点,它允许您使用通配符将任何操作与路线的任何部分匹配。

要捕获所有剩余路由,只需将低优先级路由映射定义为最后一个路由config/routes.rb

在 Rails 3 中: match "*path" => 'error#handle404'

在 Rails 2 中: map.connect "*path", :controller => 'error', :action => 'handle404'

params[:path]将包含匹配的部分。

于 2010-12-25T05:31:41.517 回答
4

如果您不需要动态错误页面,只需编辑public/404.htmlpublic/505.html. 如果你这样做,请参阅 Reza.mp 的答案。

于 2010-12-31T09:43:06.090 回答