Are you eager to elevate your security skills and safeguard your applications
against cyber threats? I created a Rails Security course is designed
specifically for developers like you who aim to build robust, secure Rails
applications!
Buy my course: Security for Rails Developers.
Buy my course: Security for Rails Developers.
rescue_from
is a very useful method in Rails. It lets us to catch exceptions and pass them to a callback or a block. A typical usecase is to handle ActiveRecord::RecordNotFound
errors like in this example:
FooController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: not_found
private
def not_found
message = "Foo with ID #{params[:id]} not found."
logger.error message
redirect_to not_found_url, info: message
end
end
ActiveRecord::RecordNotFound
raised in the scope of the FooController
it will be caught and the notfound method will log the event than redirect to the notfound page with a message to display in the browser.
Since rescue_from
works with a block too we can refactor the above as follows:
FooController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound do |exception|
message = "Foo with ID #{params[:id]} not found."
logger.error message
redirect_to not_found_url, info: message
end
end
rescue_from CanCan::AccessDenied do |exception|
redirect_to root_url, :alert => exception.message
end
ActionController::Base
you just need to mixin the ActiveSupport::Rescuable
:
class Foo
include ActiveSupport::Rescuable
end
Or follow me on Twitter
I run an indie startup providing vulnerability scanning for your Ruby on Rails app.
It is free to use at the moment, and I am grateful for any feedback about it.If you would like to give it a spin, you can do it here: Vulnerability Scanning for your Ruby on Rails app!