停止管道运营商链
问题描述:
我有这样停止管道运营商链
check_file(url) |>test |> foo
TRE功能check_file返回
{:ok,_} or {:error,_}
我有一个模式匹配
def test({:ok,_}) do
IO.puts "ok";
end
def test({:error,_}) do
IO.puts "KO, debug and stop!";
end
如果我有两个功能:错误我不想调用我的最后一个函数(foo),但我想在调试中显示错误
我可以这样做吗?
答
可以使用with声明灵药这样
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
答
只需用一个简单的例子来代替:
case check_file(url) do
{:ok, file} ->
IO.puts "ok"
foo(file)
{:error, _} ->
IO.puts "KO, debug and stop!"
end
答
也许最简单的办法就是支持添加到{:error, _}
模式运作foo
:
def foo({:ok,_}) do
IO.puts "do the stuff";
end
def foo({:error,_}), do: {:error, []}
但在这种解决方案中,您需要从test
返回{:error}
。
答
在其他答案中没有提到的是,你可以在test
函数中引发一些特定的错误,然后用管道中的任何代码来捕获它。只有这样,你才能真正阻止任意长长的管道。
但我不会这样做。我宁愿编写我的程序,因为我不需要通过提出错误来停止管道。
感谢您的回复,以这种方式我必须将这个条件添加到每个函数'check_file(url)|> test |> foo |> bar |> buz'right?感谢 – monkeyUser
这取决于函数返回的内容。如果他们返回'''{:ok,something}˚˚˚或˚˚˚{:error,some_error}'''你应该使用'''with''',因为你可以处理多个这些元组并为所有功能在一个地方进行错误处理。 – Pfitz