Home > tech > A Bit Deeper Into Rails 3.0 Error Pages

A Bit Deeper Into Rails 3.0 Error Pages

In the previos post I shared a bit of a hack to have our ApplicationController send errors to the static
404 and 500 pages. After road-testing that solution for a bit and getting some
feed back I would like to offer a slight polishing of that previous idea where errors are redirected to
an ErrorController and the error page is dynamically rendered.

First, add the handler methods to the base ApplicationController as in the last post. Notice that
they are different! They point to a controller named error.

class ApplicationController  :error, :action => :server_error
  end

  def method_missing(id, *args)
    redirect_to :controller => :error, :action => :not_found
  end
end

Now, what I glossed over in the previous post, this error controller will have two actions (and views which
are not shown here). Notice that we also have defined rescue_with_handler in ErrorController
as well as in ApplicationController. In the rare case that we cannot render the error pages, for
example the navigation bar uses a database table and the error is that the database is down, we need a way to
fail back to the static /500.html page. Otherwise we will recursively exhaust the call stack in the
Ruby VM.

class ErrorController < ApplicationController
  def not_found
  end

  def server_error
  end

  def rescue_with_handler(exception)
    redirect_to '/500.html'
  end
end

Finally, add a line in your config/routes.rb file to send anything not already captured to the
ErrorController‘s action note_found.

match ':action', :controller => :error, :action => :not_found

I choose to pepper this sort of thing with logging statments at least until I’m sure it’s working correctly. Enjoy!

Advertisement
Categories: tech Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.