Howto raise and rescue Exceptions in Ruby on Rails

Hello ! This week we talk about exceptions. An Exception is an event that could be thrown in particular circumstances and that goes up all the application stack until someone rescue it.

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

end

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

def rescue_action_in_public(exception)

if exception.to_s =~ /PersonalException/

# do your stuff here

else

raise exception

end

end

def local_request?

false

end

end

Some notes

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.

Conclusion

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.

Leave a Comment

*