Custom Error Page - Ruby on Rails

隐身守侯 提交于 2019-11-30 06:25:57

问题


I am trying to setup a custom error page in my website. I am following the guidelines atPerfectLine Blog.

It works in the case where the controller exists, but the id does not exist. For example, I have a blog controller and id 4 does not exist. It shows the custom error page

But it does not exist in the case, where controller itself does not exist. For example, if I type some random controller with a numeric id does not gets caught by the methods I have setup in the application controller to re-route the custom error pages. In this case, I get an

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

in the terminal and the default error page that comes with 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

Could you please help me. Thanks.


回答1:


You can do that with route globbing in rails, It lets you match any action to any part of a route using wildcards.

To catch all remaining routes, just define a low priority route mapping as the last route in config/routes.rb:

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

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

params[:path] will contain the matching part.




回答2:


If you don't need dynamic error pages, just edit public/404.html and public/505.html. If you do, see Reza.mp's answer.



来源:https://stackoverflow.com/questions/4525715/custom-error-page-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!