Exceptions are commonly used for very exceptional events and could happen that we need to create a new Exception class for our programming purpose.
Ok, let’s suppose we need to raise a “PersonalException” exception at some point and rescue it in exactly the same way for all the controllers, the code is here:
Creating the Exception class
To create our “PersonalException” we just need to extend “Exception” class.
class PersonalException < Exception
Raise our Exception
raise PersonalException.new, "message"
Rescue our exception
We can do this by overwriting rescue_action_in_public and local_request?
functions to our application.rb file:
class ApplicationController < ActionController::Base
if exception.to_s =~ /PersonalException/
# do your stuff here
As wrote on the Ruby on Rails wiki when you test this in development mode be sure to set to false this line in your “environments/development.rb”
config.action_controller.consider_all_requests_local = false
Also, if the server is on the same machine you’re developing you need to use the “-b ” option assoicated with your lan ip ( no 127.0.0.1 neither localhost) when starting the WEBrick server.
I’m still looking on how variables stored in our PersonalException instance can be retrieved. So, if someone wants to make suggestions please post a comment.