Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'halt' (Plug.Conn.halt/1) does not stop the call chain after a redirect in controller

I have a "halt/1" in a controller based on some logic but not in a plug. Sadly, it does redirect, but also runs the code after the redirect.

if true do
  conn
    |> put_flash(:error, "Sorry, entered wrong")
    |> redirect(to: route_path(conn, :show, model))
    |> halt #this does not work :(
else
   _ #something
end

update_another_model() #this is executed
render(conn, "abc.html", model: model) #even this is executed

I actually need the call to terminate after the redirect, any ideas?

like image 720
Devaroop Avatar asked Jul 26 '16 12:07

Devaroop


2 Answers

There is no return in Elixir - you cannot exit from a function early. If you need that, then refactor your if in such a way that all the statements that need not be executed are in the else branch.

if condtition() do
  conn
    |> put_flash(:error, "Sorry, entered wrong")
    |> redirect(to: route_path(conn, :show, model))
else
  update_another_model()
  render(conn, "abc.html", model: model)
end

If condition() is true the first branch executes and the result of redirect is returned (a response indicating a redirect). If it's false then the second branch returns the result of render.

Also note that if there is anything after the if then it will be executed regardless of which branch is taken and the result of that thing will be returned from the action - probably not what you want.

like image 118
Paweł Obrok Avatar answered Nov 15 '22 02:11

Paweł Obrok


There is no halt/0. You are actually calling Plug.Conn.halt/1 (note that you are using the pipe operator (|>) to pass in the variable conn that i assume matches %Plug.Conn{}).

Plug.Conn.halt/1 will only stop plugs following your current plug from executing (remember that ultimately controller methods are also just plugs, and that plugs are always composable).

You should refactor this so that all action you want to happen if the statement doesn't hold are in the else block.

like image 45
Sam Mercier Avatar answered Nov 15 '22 04:11

Sam Mercier