Custom Rescue Templates for Rails

  • Posted by Mike Naberezny in Ruby

    Ruby on Rails provides a nice feature for development that displays neatly formatted error screens when an exception is raised. This screen is very convenient because it can usually show the line number where the error occurred, different views of the backtrace, and other useful troubleshooting data including the environment, session, and request/response objects. Having this information is not only useful but provides a feeling of stability and more graceful error handling compared to something like PHP’s raw errors (enhanceable by xdebug).

    The default Ruby on Rails error screens are very functional but are also quite plain. Some Rails developers, particularly those working on teams, may wish to tailor them to provide consistent styling with their application or to display additional application-specific information for the development environment.

    The Rails error screens are generated by views bundled inside ActionController called rescue templates. David recently committed my first patch to Edge Rails in changeset 5243. Now, creating your own custom rescue templates is very straightforward.

    Begin by copying the default rescue templates to a new directory under app/views in your Rails project. I recommend app/views/rescues. The rescue templates are found in ActionController, which is under vendor/rails for projects on Edge Rails or that have frozen Rails.

    $ mkdir app/views/rescues
    $ cp vendor/rails/actionpack/lib/action_controller/templates/rescues/* \
        app/views/rescues
    

    Next, add the following snippet to your ApplicationController:

    protected
      def rescues_path(template_name)
        "#{template_root}/rescues/#{template_name}.rhtml"
      end
    

    The templates will now be taken from your app/views/rescues directory and can be modified to taste. To test, browse to any action that will raise an exception.

    As of Rails 1.1.6, the instructions above will only work on Edge Rails but will work in the next stable version. See the ticket for more information to patch 1.1.6 and earlier versions.

    You are encouraged to read the API documentation for ActionController::Rescue to understand how and when the rescue templates are rendered. It is important to note that for security, the rescue templates should never be shown to the public and thus only ever rendered when a request is considered local.

    Update: This tutorial was featured on Riding Rails, the Ruby on Rails weblog.

    Update: These instructions work with the stable release of Rails since 1.2.

    Update: As of changeset 6120, template_root is now view_paths.first