Skip to content

Instantly share code, notes, and snippets.

@seth-macpherson
Forked from punund/gist:1034276
Created May 16, 2012 11:30
Show Gist options
  • Save seth-macpherson/2709681 to your computer and use it in GitHub Desktop.
Save seth-macpherson/2709681 to your computer and use it in GitHub Desktop.
Proper exception handling in Rails 3
# coding: utf-8
class ApplicationController < ActionController::Base
protect_from_forgery
rescue_from Exception, :with => :handle_exceptions
private
def handle_exceptions(e)
case e
when CanCan::AccessDenied
authenticate_user!
when ActiveRecord::RecordNotFound
not_found
else
internal_error(e)
end
end
def not_found
# Just render view
render 'application/not_found', :status => 404
end
def internal_error(exception)
if RAILS_ENV == 'production'
# Send message to admin email via exception_notification
request.env['exception_notifier.options'] = {
:sender_address => "sender@example.com",
:exception_recipients => "recipient@example.com"
}
ExceptionNotifier::Notifier.exception_notification(request.env, exception).deliver
# And just render view
render :layout => 'layouts/internal_error',
:template => 'application/internal_error',
:status => 500
else
throw exception
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment