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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With