work with rescue in Rails

Adnan picture Adnan · Apr 2, 2010 · Viewed 40.9k times · Source

I am working with the following piece;

def index
  @user = User.find(params[:id]) 
  rescue
    flash[:notice] = "ERROR"
    redirect_to(:action => 'index')
  else 
    flash[:notice] = "OK"
    redirect_to(:action => 'index')
end

Now I either case whether I have a correct ID or not, I am always getting "OK" in my view, what am I doing wrong?

I need that when I have no ID in the DB to show "ERROR". I have also tried to use rescue ActiveRecord::RecordNotFound but same happens.

All help is appreciated.

Answer

shingara picture shingara · Apr 2, 2010

All code after the end of the rescue block is interpreted only if there are no returns in the rescue block. So you can call return at the end of your rescue block.

def index
  begin
    @user = User.find(params[:id]) 
  rescue
    flash[:notice] = "ERROR"
    redirect_to(:action => 'index')
    return
  end
  flash[:notice] = "OK"
  redirect_to(:action => 'index')
end

or

def index
  @user = User.find(params[:id]) 
  # after is interpret only if no exception before
  flash[:notice] = "OK"
  redirect_to(:action => 'index')
rescue
  flash[:notice] = "ERROR"
  redirect_to(:action => 'index')
end

But in your case the better is to use rescue_from or rescue_in_public

like

class UserController < ApplicationController
  def rescue_in_public(exception)
    flash[:notice] = "ERROR"
    redirect_to(:action => 'index')
  end

  def index
    @user = User.find(params[:id]) 
    flash[:notice] = "OK"
    redirect_to(:action => 'index')
  end
end

But the using of rescue_in_public is not really good advice