Skip to content

Exception Handling

ryanb edited this page Aug 13, 2010 · 1 revision

The CanCan::AccessDenied exception is raised when calling authorize! in the controller and the user is not able to perform the given action. A message can optionally be provided.

authorize! :read, Article, :message => "Unable to read this article."

This exception can also be raised manually if you want more custom behavior.

raise"Not authorized!", :read, Article)

You can catch this exception and modify its behavior in the ApplicationController. For example here we set the error message to a flash and redirect to the home page.

class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    flash[:error] = exception.message
    redirect_to root_url

The action and subject can be retrieved through the exception to customize the behavior further.

exception.action # => :read
exception.subject # => Article

The default error message can also be customized through the exception. This will be used if no message was provided.

exception.default_message = "Default error message"
exception.message # => "Default error message"

If you prefer to return the 403 Forbidden HTTP code, create a public/403.html file and write a rescue_from statement like this example in ApplicationController:

class ApplicationController < ActionController::Base
  rescue_from CanCan::AccessDenied do |exception|
    render :file => "#{RAILS_ROOT}/public/403.html", :status => 403

403.html must be pure HTML, CSS, and JavaScript--not a template. The fields of the exception are not available to it.

See Authorization in Web Services for rescuing exceptions for XML responses.

Something went wrong with that request. Please try again.