Throw your own exceptions
February 24th, 2008 by pyrat
Throwing and catching exceptions can be a good design pattern in your rails app. Especially when you want to be able to deal with the unexpected in a clean way. Overuse is a no no as with most techniques but it is nice here and there.
I find that a good idea is to make your own exceptions when writing a rails app. This means that standard low level exceptions which often should not be caught are not.
eg.
(in config/initializers/custom_config.rb)
class ApplicationError < RuntimeError end
This way in your application code you can do something like the following
begin @user = User.find_by_password_reset_code(params[:id]) raise ApplicationError if @user.nil? rescue ApplicationError => msg flash[:message] = "Sorry - That is an invalid password reset code. Please check your code and try again. (Perhaps your email client inserted a carriage return?" redirect_to logins_url end
In other news I have started testing deploying with git and capistrano. It is blazingly fast even for a full checkout. I cant get :remote_cache deploy via working due to an ancient version of git on LTS 6.06. But event with full checkout this is faster than deploy_via :remote_cache with subversion! (This is with 2 slices on a local network.)
March 20th, 2008 at 5:48 pm
This is definitely the way to go. I modified the OpenID plugin to throw errors at different points. It makes it much easier to catch those errors in the controller and provide an appropriate message.
Some have said that errors are slower than inline logic, but hopefully errors happen infrequently enough that it doesn’t matter.