问题
I am trying to implement custom error handling as well as use CanCan. When a user reaches an area they aren't allowed to go to, a CanCan::AccessDenied error is thrown and they should be sent to the root url. Instead, 'rescue_from Exception' captures the CanCan::AccessDenied and the user gets a 500 error. What am I doing wrong?
#application_controller.rb
rescue_from CanCan::AccessDenied do |exception|
redirect_to main_app.root_url, :alert => exception.message
end
rescue_from Exception,
:with => :render_error
rescue_from Mongoid::Errors::DocumentNotFound,
:with => :render_not_found
rescue_from ActionController::RoutingError,
:with => :render_not_found
rescue_from ActionController::UnknownController,
:with => :render_not_found
rescue_from AbstractController::ActionNotFound,
:with => :render_not_found
def render_not_found(exception)
render :template => "/errors/404.html",
:layout => 'errors.html',
:status => 404
end
def render_error(exception)
render :template => "/errors/500.html",
:layout => 'errors.html',
:status => 500
end
回答1:
Did you try reordering rescue_from exceptions/errors, more generic first, more specific later, e.g.
rescue_from StandardError,
:with => :render_error
rescue_from Mongoid::Errors::DocumentNotFound,
:with => :render_not_found
rescue_from ActionController::RoutingError,
:with => :render_not_found
rescue_from ActionController::UnknownController,
:with => :render_not_found
rescue_from AbstractController::ActionNotFound,
:with => :render_not_found
rescue_from CanCan::AccessDenied do |exception|
redirect_to main_app.root_url, :alert => exception.message
end
Note: You might want to replace generic Exception with StandardError.
来源:https://stackoverflow.com/questions/20094078/custom-error-handling-and-cancan