CanCan is an authorization library for Ruby on Rails that defines the authorization of specific resources for multiple users. Let’s talk about Exception handling in CanCan.
The CanCan::AccessDenied
exception is raised when authorize!
is called, and the user is unable to perform the given action. The following code shows how the exceptions are raised:
authorize! :read, Article, :message => "Can not read the Article"
These exceptions can also be raised manually using:
raise CanCan::AccessDenied.new("User Access Denied!", :read, Article)
This method enables a more custom approach. Other functionalities can be added (like using internalization to raise relevant errors) to make the code more robust. Take a look at the example below:
# in config/locales/en.yml
en:
unauthorized:
default: "Error"
manage:
all: "Not authorized to %{action}."
user: "You can only manage your account."
update:
project: "You can only update your project."
The %{action}
can be used to pass a variable that customizes the message using the given template.
You can catch an error and modify its behavior in the ApplicationController
.
The action and subject can be retrieved through:
exception.action =>
exception.subject.class =>
The default message can be set by using:
exception.default_message = "Default error message"
exception.message # => "Default error message"
In this way, errors like HTTP 404 and others can be generated.
Free Resources