這裏不需要try
/catch
。用case
聲明匹配響應一個簡單的遞歸函數就足夠了:
defmodule A do
# A function that returns `{:ok}` a third of the times it's called.
def ping, do: if :random.uniform(3) == 1, do: {:ok}, else: {:error}
# 5 attempts.
def test(), do: test(5)
# If 1 attempt is left, just return whatever `ping` returns.
def test(1), do: ping()
# If more than one attempts are left.
def test(n) do
# Print remaining attempts for debugging.
IO.inspect {n}
# Call `ping`.
case ping() do
# Return {:ok} if it succeeded.
{:ok} -> {:ok}
# Otherwise recurse with 1 less attempt remaining.
{:error} -> test(n - 1)
end
end
end
測試:
iex(1)> A.test
{5}
{4}
{3}
{2}
{:ok}
iex(2)> A.test
{5}
{4}
{3}
{2}
{:error}
iex(3)> A.test
{5}
{:ok}
iex(4)> A.test
{5}
{:ok}
iex(5)> A.test
{5}
{4}
{:ok}
謝謝您的回答!正是我在找什麼。祝你今天愉快! – Ilya