Saturday, February 28, 2009

Rails 2.0 and cool error handling

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:

def rescue_action_in_public(exception)
  case exception
  when ::ActiveRecord::RecordNotFound
    render :file => "#{Rails.public_path}/404.html", :status => 404
    render :file => "#{Rails.public_path}/500.html", :status => 500

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.

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

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.

No comments:

Post a Comment