Is there any good best practices for exception handling in rails?
I'm currently on Rails 2.3.5 and I'm trying rescue_from exceptions as neat as possible in my Application.
My ApplicationController rescues look like this now:
rescue_from Acl9::AccessDenied, :with => :access_denied
rescue_from Exceptions::NotPartOfGroup, :with => :not_par开发者_开发知识库t_of_group
rescue_from Exceptions::SomethingWentWrong, :with => :something_went_wrong
rescue_from ActiveRecord::RecordNotFound, :with => :something_went_wrong
rescue_from ActionController::UnknownAction, :with => :something_went_wrong
rescue_from ActionController::UnknownController, :with => :something_went_wrong
rescue_from ActionController::RoutingError, :with => :something_went_wrong
I also want to be able to catch any exceptions no listed above. Is there recommended way I should be writing my rescues?
Thanks
You can catch more generic exceptions, but you have to put them at top, as expained here
For example, to catch all other exceptions, you can do
rescue_from Exception, :with => :error_generic
rescue_from ... #all others rescues
But if you do that, make sure you at least log the exception, or you will never know, what is wrong with your app:
def error_generic(exception)
log_error(exception)
#your rescue code
end
also, you can define multiple exception classes in row for one handler:
rescue_from Exceptions::SomethingWentWrong, ActiveRecord::RecordNotFound, ... , :with => :something_went_wrong
maybe exception notifier plugin can help you some way
You can define a hook method in ApplicationController like this:
def rescue_action_in_public(exception)
case exception
when ActiveRecord::RecordNotFound, ActionController::UnknownAction, ActionController::RoutingError
redirect_to errors_path(404), :status=>301
else
redirect_to errors_path(500)
end
end
I recently released a rails 3 gem (egregious) that will catch common exceptions using rescue_from and provide well defined http status codes and error responses for html, json and xml.
By default it attempts to do the right thing. You can add any or change any exceptions and their status codes in an initializer.
This may or may not fit your needs. https://github.com/voomify/egregious
精彩评论