Rescuing errors in Rails 3.2 with `config.exceptions_app = self.routes`

大城市里の小女人 提交于 2019-12-31 10:47:23

问题


As per this post:

http://blog.plataformatec.com.br/2012/01/my-five-favorite-hidden-features-in-rails-3-2/

The newest way to handle errors looks like this:

# application.rb:
config.exceptions_app = self.routes

#routes.rb
match "/404", to: "site#not_found"

However, he doesn't address the fact that the rails error app also handles 500 errors, 422 errors (and possibly other errors funneled to those two pages?)

So I've hacked together a solution that looks like this:

# routes.rb
rack_error_handler = ActionDispatch::PublicExceptions.new('public/')
match "/422" => rack_error_handler
match "/500" => rack_error_handler

It's good in that it keeps my 500 pages lightweight.

Are there other errors I should be catching as well? My understanding is that although the 500 page will now be using two rack apps, it is still safely isolated from the main Rails App enough. Is this strong?

Thanks!


回答1:


I add the rescue froms in the application controller

  if Rails.env.production?
    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
    rescue_from ActionView::MissingTemplate, :with => :render_not_found
  end

  def render_not_found(exception)
    logger.info("render_not_found: #{exception.inspect}")
    redirect_to root_path, :notice => 'The page was not found.'
  end

and then add a errors_controller to rescue the route errors adding this to the bottom of my routes file

  match "*path", :to => "errors#routing_error"



回答2:


Try this

Update config/application.rb

config.exceptions_app = self.routes

and your route file

match "/404", :to => "errors#not_found"


来源:https://stackoverflow.com/questions/13242947/rescuing-errors-in-rails-3-2-with-config-exceptions-app-self-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!