Skip to content

Instantly share code, notes, and snippets.

@punund
Created June 19, 2011 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save punund/1034276 to your computer and use it in GitHub Desktop.
Save punund/1034276 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
@narc88
Copy link

narc88 commented Feb 11, 2013

great explanation!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment