在管道操作员中停止链

时间:2017-10-05 12:03:48

标签: elixir

我有像这样的tre函数

check_file(url) |>test |> foo

check_file return

{:ok,_} or {:error,_}

我有两个模式匹配功能

  def test({:ok,_}) do
     IO.puts "ok";
  end

  def test({:error,_}) do
     IO.puts "KO, debug and stop!";
  end

如果我得到:错误我不想调用我的上一个函数(foo)但是我想在Debug中显示错误

我可以这样做吗?

4 个答案:

答案 0 :(得分:1)

您可以像elixir一样使用react-native-rename语句

with {:ok, file} <- check_file(url) do
    file |> foo |> foo
else 
  IO.puts "KO, debug and stop!"
end

如果test也返回 {:ok, something}元组,则此功能尤其有用。然后,您可以展开with

如果您只能在check_file(url)方法的开头出现错误,可以执行以下简单的解决方案:

def test({:ok,file}) do
   IO.puts "ok";
   do_your_stuff_with_the_file()t |> foo
end

def test({:error,_}) do
     IO.puts "KO, debug and stop!";
  end

答案 1 :(得分:0)

只需使用简单的案例:

case check_file(url) do
  {:ok, file} ->
    IO.puts "ok"
    foo(file)
  {:error, _} ->
    IO.puts "KO, debug and stop!"
end

答案 2 :(得分:0)

可能最简单的方法是将{:error, _}模式的支持添加到函数foo

  def foo({:ok,_}) do
     IO.puts "do the stuff";
  end
  def foo({:error,_}), do: {:error, []}

但是在这种解决方案中,您需要从{:error}返回test

答案 3 :(得分:0)

其他答案中没有提到的是,您可以在test函数中引发一些特定错误,然后在管道中的任何代码包装中捕获它。只有这样你才能真正阻止任意长管道。

但我不会这样做。我宁愿用我不需要通过引发错误来阻止管道来编写我的程序。

相关问题