2013-11-20 72 views
3

我想实现自定义错误处理以及使用CanCan。当用户到达不允许去的区域时,会抛出CanCan :: AccessDenied错误,并将它们发送到根网址。相反,'rescue_from Exception'捕获CanCan :: AccessDenied,并且用户得到500错误。我究竟做错了什么?自定义错误处理和cancan

#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 

回答

0

是否尝试对rescue_from异常/错误进行重新排序,更通用的第一个,稍后更具体的例如,

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 

注意:您可能希望用StandardError替换通用异常。

+0

此解决方案适用于我。正如你所注意的那样,Rails文档清楚地表明该命令很重要。 –