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

时间:2016-07-26 12:22:22

标签: redirect elixir phoenix-framework

我有一个"停止/ 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

我实际上需要在重定向之后终止调用,任何想法?

2 个答案:

答案 0 :(得分:4)

Elixir中没有return - 您无法提前退出某个功能。如果你需要,那么重构你的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

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

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

答案 1 :(得分:1)

没有停止/ 0。您实际上正在调用Plug.Conn.halt/1(请注意,您正在使用管道运算符(|>)传入我假设匹配conn)的变量%Plug.Conn{}

Plug.Conn.halt/1只会在当前插件执行后停止插件(请记住,最终控制器方法也只是插头,并且插件总是可组合的。)

您应该重构这一点,以便在语句未保留的情况下您想要发生的所有操作都在else块中。