在开发阶段,如果发生错误时,都会出现错误提示页面,比如:RecordNotFound之类的,虽然这些错误方便开发进行debug,但是等产品上线时,如果还是出现这些页面,对于用户来说是很不友好的。
所以必须定制错误跳转到404和500
下面示范在development下开发的404和500跳转:
首先在 config/environment/development.rb中,找到下面这句代码,将其设为false
config.consider_all_requests_local = false # rails 4.0
或者
config.action_controller.consider_all_requests_local = false # rails 3.0
接着修改route.rb, 在route.rb中增加下面这句:(注意:放到最后一行)
# make sure this rule is the last one get '*path' => proc { |env| Rails.env.development? ? (raise ActionController::RoutingError, %{No route matches "#{env["PATH_INFO"]}"}) : ApplicationController.action(:render_not_found).call(env) }
然后在application_controller.rb中增加下面代码:
1 def self.rescue_errors 2 rescue_from Exception, :with => :render_error 3 rescue_from RuntimeError, :with => :render_error 4 rescue_from ActiveRecord::RecordNotFound, :with => :render_not_found 5 rescue_from ActionController::RoutingError, :with => :render_not_found 6 rescue_from ActionController::UnknownController, :with => :render_not_found 7 rescue_from ActionController::UnknownAction, :with => :render_not_found 8 end 9 10 rescue_errors unless Rails.env.development? 11 12 def render_not_found(exception = nil) 13 render :file => "/public/404.html", :status => 404 14 end 15 16 def render_error(exception = nil) 17 render :file => "/public/500.html", :status => 500 18 end
这样就完成404和500的定制跳转啦! over! @_@!!
注:production环境下的404和500跳转已经自动配置了。
参考链接:
http://www.perfectline.ee/blog/custom-dynamic-error-pages-in-ruby-on-rails
http://chen-miao.iteye.com/blog/1456355
http://www.iteye.com/topic/191531