ruby-on-rails - 自定义错误页面 - Ruby on Rails

标签 ruby-on-rails ruby ruby-on-rails-3 custom-error-pages

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

在controller存在,但id不存在的情况下有效。例如,我有一个博客 Controller ,id 4 不存在。它显示自定义错误页面

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

ActionController::RoutingError(没有路由匹配“/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

你能帮帮我吗?谢谢。

最佳答案

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

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

在 Rails 3 中: 匹配“*路径”=> 'error#handle404'

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

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

关于ruby-on-rails - 自定义错误页面 - Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4525715/

相关文章:

ruby-on-rails - 多个子域不断重定向到根路径

ruby-on-rails - 使用 channel 推送的 websocket rails

ruby-on-rails - 在 ActiveRecord 对象上注入(inject)

ruby-on-rails - 使用前端服务器和不同机器上的音频文件在 LAN 上运行 Ruby on rails 应用程序的流式音频?

Ruby 线程 : how to catch an exception without calling . 加入?

ruby-on-rails - 在 Rails 中渲染大量 ActiveRecord 对象

ruby-on-rails - 预期响应为 < :success>, 但为 <301>

ruby-on-rails - Phusion Passenger 中是否有某种机制可以防止整个应用程序宕机?

ruby-on-rails - 在 Rails 中查找未翻译的语言环境

ruby-on-rails-3 - 删除链接转到显示方法