Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom error handling and cancan

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
like image 222
Jeremy Lynch Avatar asked Mar 16 '26 14:03

Jeremy Lynch


1 Answers

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.

like image 138
nevenc Avatar answered Mar 19 '26 04:03

nevenc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!