Friday, August 1, 2008

Custom 404 Pages - Rails 404 Status

Sometimes your application hits it where it doesn't know what to render. Perhaps your user tried to access so URL from memory and spelled it wrong. Maybe they tried /user/john instead of /users/john. Whatever happens, they'll be getting some sort of error. Fortunately for you, you can control this error without much work. Add this to the bottom of your routes.rb file.

map.connect '*path', :controller => 'application', :action => 'rescue_404' unless ::ActionController::Base.consider_all_requests_local

Then add to your application.rb

def rescue_404

def rescue_action_in_public(exception)
case exception
when CustomNotFoundError, ::ActionController::UnknownAction then
#render_with_layout "shared/error404", 404, "standard"
render :template => "shared/error404", :layout => "standard", :status => "404"
@message = exception
render :template => "shared/error", :layout => "standard", :status => "500"

def local_request?
return false

Sometimes you may want to throw a 404 yourself. For example if they go to /wiki/doesnotexist you can render your own page. Use something as simple as:

render :action => "something", :status => 404

or as simple as

render :file => "#{RAILS_ROOT}/public/404.html", :status => 404 and return