Graceful 404s in Rails 2.0

October 8th, 2007 by Trevor

With the upcoming Rails 2.0: Preview Release starting to get some attention, I thought I'd take a moment to play with some of the new features. One of my favorite additions is the new exception handling stuff. It works just like a before_filter, so you'll pick it up straight away.

Action Pack: Exception handling:

Lots of common exceptions would do better to be rescued at a shared level rather than per action. This has always been possible by overwriting rescue_action_in_public, but then you had to roll out your own case statement and call super. Bah. So now we have a class level macro called rescue_from, which you can use to declaratively point certain exceptions to a given action.

The following is quick example you can use to catch 404 Record Not Found errors. It will catch all 404s on your site and display a nice message, instead of an ugly white page of death:

file-not-found-1.jpeg

Simply dip into the ApplicationController and add the following code:

class ApplicationController < ActionController::Base
 
  rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
 
  # ...
 
  def record_not_found
    flash[:notice] = "Sorry, the page you requested was not found."
    redirect_to root_path
  end
 
  # ...
 
end

...to display a nice message within your app:

file-not-found-2.jpeg

...and there you have it: Easy as Pie(tm) Record Not Found exception handling.

P.S.

This also takes advantage of my favorite tiny addition to Rails, map.root. I didn't see this mentioned in the release announcement, but it's covered in the video of the Railsconf Europe '07 video.

Instead of this:

map.home '', :controller => 'home'

...you can now do this:

map.root :controller => 'home'

It's not a big change, but it's just... nice, isn't it?

Comments

Posting code? Please use Pastie.

Have a question? Please visit the Forum.

1 Comment

  1. [...] almost effortless » Graceful 404s in Rails 2.0 An explanation of #rescue_from, which was added in Rails 2.0, and is a really rather lovely way of handling all kinds of custom exception and making them not suck. (tags: rails ruby rubyonrails routing redirect) [...]