Custom error handling and cancan

喜夏-厌秋 提交于 2019-12-10 21:55:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!