您的位置:首页 > 编程语言 > Ruby

ruby -- 进阶学习(九)定制错误跳转404和500

2013-08-18 17:25 239 查看
在开发阶段,如果发生错误时,都会出现错误提示页面,比如: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中增加下面代码:

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 :file => "/public/404.html", :status => 404
end

def render_error(exception = nil)
render :file => "/public/500.html", :status => 500
end


这样就完成404和500的定制跳转啦! over! @_@!!

注:production环境下的404和500跳转已经自动配置了。

参考链接:

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

/article/4071163.html

http://www.iteye.com/topic/191531
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: