124

Tom Milewski

Custom Error Pages in Rails

The standard error pages in Ruby on Rails do not allow for enough customization and for a framework that advocates DRY (Don’t Repeat Yourself) techniques, well, it’s somewhat of a problem.

The standard error pages in Ruby on Rails do not allow for enough customization and for a framework that advocates DRY (Don’t Repeat Yourself) techniques, well, it’s somewhat of a problem. You aren’t able to embed dynamic code and because of this you also have to repeat the code for your layouts.

So how do we fix this?

The Controller

In Rails we much override render_optional_error_file.

So, in app/controllers/application_controller.rb we must add the following code:

What this does is it recieves the error code and, rather than send out the static error pages to the client, it sends out the new rendered error pages located in the views.

The Views

According to the code above we will need to create a folder within views called errors. We will then create the following views:

What you put in these views is entirely up to you.

Testing

In order to test this on your local machine you must insert the following code also into app/controllers/application_controller.rb:
Just remember to remove this last bit of code before pushing your application to your staging and/or production environments!

One Response

You can follow the comments for this article with the RSS 2.0 feed.

Thanks Tom… great post. Totally got me headed in the right direction on this. Couple notes that will hopefully help others. On my setup (Rails 2.3.2 app):”def rescue_optional_error_file(status_code)” should be “def render_optional_error_file(status_code)” and (at least in my case) where you defined known_codes I needed to define them as “404 Not Found” for example as opposed to just “404″. Just for clarity (probably obvious to most), need to put app in production mode in order to test… script/server -e production.

1 Dan Zitting July 18, 2009 1:50 am

Categories

Content © Tom Milewski
Proudly powered by WordPress
Theme designed by Artisan Themes

Entries (RSS)
Comments (RSS)

19 queries.
1.064 seconds.