f l a m e . o r g

organized flames

Rails 2.0 and cool error handling

Posted on February 28, 2009

Rails is a great framework, but it has gained something of a bad reputation in terms of error reporting. Everyone has seen them – those ugly 500-status “we’re sorry, but something has gone wrong” messages.

In a finished application, this just doesn’t cut it. It used to be necessary to trap the error using something like this:

1 def rescue_action_in_public(exception)
2   case exception
3   when ::ActiveRecord::RecordNotFound
4     render :file => "#{Rails.public_path}/404.html", :status => 404
5   else
6     render :file => "#{Rails.public_path}/500.html", :status => 500
7   end
8 end

The problem is that, as error causes begin to pile up, this method gets messy. Plus, you might want to render something different in one controller than in another, and would either need to duplicate all the logic, put controller-specific cases in the ApplicationController, or call ApplicationController::rescue_action_in_public directly.

Enter Rails 2.x error handling. Drop this in your controller or ApplicationController.

1 rescue_from(ActiveRecord::RecordNotFound) do |e|
2   render :file => "#{Rails.public_path}/404_record_not_found.html", :status => 404
3 end

By building up a rich set of rescue_from handlers in the ApplicationController, and only overriding the ones you wish to make per-controller, you have fine-grained control. And they work exactly the same in development and testing as they do in production.