Elixir define variable in function

Hi,How to solve the conn return problem.
exception: to return a plug.Conn, all plugs must receive a connection and return a connection

def function(conn,%{ "search" => %{ "for" => value} }) do
try do 
if value=1 do
       conn |> redirect(:to controller1_path(conn, :index))
end
       conn |> redirect(:to controller2_path(conn, :index))
   	end
catch  
conn |> redirect(:to controller2_path(conn, :index))
end    end

I formatted your code… to be a little bit more readable.

def function(conn,%{ "search" => %{ "for" => value} }) do
  try do 
    if value=1 do
      conn |> redirect(:to controller1_path(conn, :index))
    end
      conn |> redirect(:to controller2_path(conn, :index))
    end
  catch  
    conn |> redirect(:to controller2_path(conn, :index))
  end
end

And You can see You use if do … end end, You should use

    if value=1 do
      conn |> redirect(:to controller1_path(conn, :index))
    else
       conn |> redirect(:to controller2_path(conn, :index))
    end

But the preferred way is not to use try catch block, but function header pattern match, like so

def function(conn,%{ "search" => %{ "for" => 1} }) do
  conn |> redirect(:to controller1_path(conn, :index))
end
def function(conn,%{ "search" => %{ "for" => _value} }) do
  conn |> redirect(:to controller2_path(conn, :index))
end
2 Likes