自定义错误页面 - Ruby on Rails [英] Custom Error Page - Ruby on Rails

查看:48
本文介绍了自定义错误页面 - Ruby on Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的网站中设置自定义错误页面.我正在遵循PerfectLine 博客.

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

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

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

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

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(没有路由匹配/randomcontrollername"):

在终端和 rails 自带的默认错误页面中.

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

你能帮帮我吗?谢谢.

推荐答案

您可以使用 rails 中的路由通配符来实现这一点,它允许您使用通配符将任何操作与路由的任何部分进行匹配.

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

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

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

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

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

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

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

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

这篇关于自定义错误页面 - Ruby on Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆