Rails 3 如何定制 404 and 500 错误页面

51 篇文章 0 订阅

Rails 3 如何定制 404 and 500 错误页面

 

 

application_controller.rb 中使用rescue_from 可以完成大部分工作:

 

class ApplicationController < ActionController::Base def self.rescue_errors rescue_from Exception, :with => :render_error rescue_from RuntimeError, :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 rescue_errors unless Rails.env.development? def render_not_found(exception = nil) render :template => "errors/404", :status => 404, :layout => 'public' end def render_error(exception = nil) render :template => "errors/500", :status => 500, :layout => 'public' end end

 

 

 ActionController::RoutingError rails 3中却不能得到预期结果,因为Rails 3使用了RackRouting的异常在ActionDispatch::ShowExceptions 中处理了,而没有传入到application controller中,

比较靠谱且简单的解决方案是在routes.rb最后加一条默认routes,指向到一个类似routing_erroraction中,但需要加多一个action感觉不是很必要,得益于rails 3 routing

的强大,可以很简单快捷方便的如此这般:

 # make sure this rule is the last one
 match '*path' => proc { |env| Rails.env.development? ? (raise ActionController::RoutingError, %{No route matches "#{env["PATH_INFO"]}"}) : ApplicationController.action(:render_not_found).call(env) }

 

即可,在development中可以仍然查看详细的异常track back方便调试。

一些给力链接:

http://www.perfectline.ee/blog/custom-dynamic-error-pages-in-ruby-on-rails

http://helderribeiro.net/?p=366

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值