manging rescues

What's the recommended way to catch errors like this:

NoMethodError in Register#confirm
Showing app/views/register/confirm.rhtml where line #4 raised:
undefined method `namen' for nil:NilClass

I get this error when someone does somethinh like:

http://…/register/confirm?email=jkdsfadslkjflksd

If I make:

  remail = params[:email]
  @user = Request.find(:first, :conditions => ["email = ?", remail])

the error occurs.

What's the prefered way to react when such an error occurs?

rescue_action_in_public

Here's what it does by default on 1.2.x... not very exciting:

http://dev.rubyonrails.org/browser/branches/1-2-stable/actionpack/lib/action_controller/rescue.rb#L50

If you're on edge you can manage this a lot easier, defining what type
of status you want returned and template you want rendered for each

http://dev.rubyonrails.org/browser/trunk/actionpack/lib/action_controller/rescue.rb#L90

Rails will use rescue_action_in_public for errors in production,
unless the the request comes from the same IP as the server. Then,
you get the standard dev-mode stack trace screen.

jochen kaechelin wrote:

remail = params[:email]
@user = Request.find(:first, :conditions => ["email = ?", remail])

the error occurs.

What's the prefered way to react when such an error occurs?

Briefly, @user might be nil, so you must guard it with "if @user" each time you use it.

I prefer to put that "if @user" line in only one place, for DRY code. I use a kind of Null Object there:

  def someone
    return @user if @user
    who = OpenStruct.new(
                      :login => '',
                      :namen => '',
                      :user_id => nil)
    def who.delete_data(r)
        false
    end
    return who
  end

Instead of using "@user" everywhere, I use "someone". If nobody is logged in, "someone" provides only methods that un-logged-in people can use. For example, if logged-in users can delete data, the line "someone.delete_data(a_record)" will delete the data if a user is logged in, and it won't do anything if nobody is logged in.

The heart of Object Oriented programming is replacing if statements with virtual methods that provide the correct behavior.

undefined method `namen' for nil:NilClass

rescue_action_in_public

Tip: Don't use rescue where you should just use if. The @user is just nil, per the contract of .find(), so use if @user to detect that. Don't let the nil run around loose until something explodes, and then rescue that!