Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 516
Peter Ehrlich Avatar asked Nov 06 '12 01:11

Peter Ehrlich


2 Answers

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"
like image 192
Davinj Avatar answered Oct 20 '22 13:10

Davinj


Try this

Update config/application.rb

config.exceptions_app = self.routes

and your route file

match "/404", :to => "errors#not_found"
like image 45
Thiyagu Avatar answered Oct 20 '22 11:10

Thiyagu