Menu

Error Reporting In Rails

February 1, 2014 - Rails

For error reporting, there’s a handy gem called exception_notification which sends you a mail every time an exception happens in your application.

If you also want to get detailed and fully customizable error reporting on a page, you’d have to do a little coding. Here’s what I use (I’d give you a link to where I’ve taken this from, but I can’t find it any longer 🙁 )

  1. Define an ErrorsController like this:
    class ErrorsController < ApplicationController
      ERRORS = [
        :internal_server_error,
        :not_found,
        :unprocessable_entity,
        :unauthorized
      ].freeze
    
      ERRORS.each do |e|
        define_method e do
          respond_to do |format|
            format.html { render e, :status => e }
            format.any { head e }
          end
        end
      end

    end

  2. Create an initializer to hook the controller into the Rails exception handling chain:
    require 'action_dispatch/middleware/show_exceptions'
    
    module ActionDispatch
      class ShowExceptions
        private
          def render_exception_with_template(env, exception)
          env['exception'] = exception
          body = ErrorsController.action(rescue_responses[exception.class.name]).call(env)
          log_error(exception)
          env.delete 'exception'
          body
        rescue Exception => e
          log_error(e)
          render_exception_without_template(env, exception)
        end
    
        alias_method_chain :render_exception, :template
      end
    end
  3. Create a view for each of the errors in ErrorsController::ERRORS (i.e. app/views/errors/not_found.html.erb etc).

Leave a Reply