Rails - Custom 404 and 500 pages and the exception_notification gem

April 27, 2012


This post was originally published in the Rambling Labs Blog on April 27, 2012.


As I explained before on the Rails 3.1 - Adding custom 404 and 500 error pages post, sometimes you might want to have a custom way to handle your not found and internal server errors. In that case we wanted to show the error with a custom template.

But, what if I have an important site from which I want to be notified if there is any error raised? There are a couple of gems for this. The one I’m most familiar with is exception_notification gem, which is easily configured as it is depicted on its README.

This gem is added to the rails middleware stack and will capture any raised error and send you an email notifying about it.

However, someone pointed out that when you set up both the custom error pages and the exception_notification, the email is never sent. This is because the exception is captured on the ApplicationController and it never gets to pass through the ExceptionNotifier middleware.

Thankfully, the solution for this is very simple and is described on the README. So, just add this method to your application_controller.rb:

class ApplicationController < ActionController::Base
  # ...

  private

  # ...

  def notify(exception)
    ExceptionNotifier::Notifier.exception_notification(request.env, exception,
      data: {message: 'an error happened'}).deliver
  end

  # ...
end

And call it from both render_404 and render_500 methods:

class ApplicationController < ActionController::Base
  # ...

  private

  def render_404(exception)
    notify exception
    # ...
  end

  def render_500(exception)
    notify exception
    # ...
  end
  # ...
end

That should do it!