FooController<ActionController::Baserescue_fromActiveRecord::RecordNotFound,with: not_foundprivatedefnot_foundmessage="Foo with ID #{params[:id]} not found."logger.errormessageredirect_tonot_found_url,info: messageendend
In the example above whenever an 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::Baserescue_fromActiveRecord::RecordNotFounddo|exception|message="Foo with ID #{params[:id]} not found."logger.errormessageredirect_tonot_found_url,info: messageendend
Another case when rescue_from comes handy is when we use cancan for authorization and we want to handle the authorization errors. We can do so by add the following to the application controller:
As you see in this case we display the exception message set by cancan.
If you want to use rescue_from from in a class which does not inherit from ActionController::Base you just need to mixin the ActiveSupport::Rescuable:
classFooincludeActiveSupport::Rescuableend
Develop the right mindset for Rails security
Avoid shipping vulnerable code by learning how to prevent security issues in your Rails applications.