`with` statement has an `else` clause
with statements are used to ensure a specific result from a function or series of functions, using the results of those functions to take actions within the with block. If a function does not return a specific result (think :error instead of :ok) then you can either define specific clauses for the things you expected to go wrong, or you can just return the result that did not conform to the with clause expectations.
This is the general form:
with {:ok, a} <- {:ok, 123} do
IO.puts "Everythings OK"
end
A with with an else block:
with {:ok, a} <- {:error, 123} do
IO.puts "Everythings OK"
else
result -> IO.puts("Not OK")
end
A with else clause with pattern matching:
with {:ok, a} <- {:error, "something went wrong"} do
IO.puts "Everythings OK"
else
{:error, message} -> IO.puts(message)
error -> IO.puts("I'm not sure what went wrong
end
A with without an else clause where the error is returned from the with block:
result = with {:ok, a} <- {:error, "something went wrong"} do
IO.puts "Everythings OK"
end
{:error, message} = result
IO.puts "This went wrong #{message}"
Tweet