'halt' (Plug.Conn.halt/1) 在控制器重定向后不会停止调用链

Dev*_*oop 5 redirect elixir phoenix-framework

我在基于某些逻辑的控制器中有一个“halt/1”,但不是在插头中。可悲的是,它确实重定向,但也在重定向后运行代码。

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
Run Code Online (Sandbox Code Playgroud)

我实际上需要在重定向后终止调用,有什么想法吗?

Paw*_*rok 5

returnElixir中没有- 您不能提前退出函数。如果你需要,那么重构你的if所有不需要执行的语句都在else分支中。

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
Run Code Online (Sandbox Code Playgroud)

如果condition()true第一个分支执行并redirect返回结果(指示重定向的响应)。如果是,false则第二个分支返回 的结果render

另请注意,如果在ifthen之后有任何内容,则无论采用哪个分支,它都会执行,并且该操作的结果将从操作中返回 - 可能不是您想要的。