ok and error tuples
A function of Elixir that may fail answers one of two tuples: {:ok, value} or {:error, reason}. The convention is not enforced by the language and every library follows it, which is why a caller reads a result with a pattern rather than with a status code, and why the same thing exists twice in the standard library: a function that answers the pair and a function whose name ends in ! that raises instead.
A function that answers with a pair
The two clauses below answer the tuple of the case they are in. The caller matches the tag first, so a failure and a success are two branches of one expression:
pairs.exs
defmodule Div do def safe(a, b) when b != 0, do: {:ok, a / b} def safe(_a, 0), do: {:error, :division_by_zero} end IO.inspect(Div.safe(10, 4)) IO.inspect(Div.safe(1, 0)) case Div.safe(1, 0) do {:ok, value} -> IO.puts("value: #{value}") {:error, reason} -> IO.puts("error: #{reason}") end
elixir pairs.exs
{:ok, 2.5}
{:error, :division_by_zero}
error: division_by_zero
The reason is an atom rather than a sentence, because the caller decides how to report it. A tuple that carries a whole error has the same shape with more in it, {:error, {:bad_input, line}} , and the caller destructures as deep as it needs. The with lesson shows the same two tuples in a chain of steps, where the first error ends the chain.
The bang version
The pair is right for a caller that can handle a failure, and a function that cannot handle it wants the crash. The convention is a second function whose name ends in ! and which raises the reason of the error tuple; inside the module one calls the other:
bang.exs
defmodule Div do def ok!(a, b) do case safe(a, b) do {:ok, value} -> value {:error, reason} -> raise ArgumentError, "division failed: #{reason}" end end defp safe(a, b) when b != 0, do: {:ok, a / b} defp safe(_a, 0), do: {:error, :division_by_zero} end IO.inspect(Div.ok!(10, 4)) try do Div.ok!(1, 0) rescue e in ArgumentError -> IO.puts("raised: #{e.message}") end
elixir bang.exs
2.5
raised: division failed: division_by_zero
File.read/1 and File.read!/1 are the canonical pair, and so are Map.fetch/2 and Map.fetch!/2, Date.from_iso8601/1 and its bang form, and dozens more. The bang version is for a program whose next line cannot work without the value, where the crash is the honest answer and the stack trace is the report.
The pair in the standard library
The two shapes appear in the calls a program makes every day. The program writes its own file so it runs on its own, and the missing file is the second case:
stdlib.exs
File.write!("notes.txt", "hi") IO.inspect(File.read("notes.txt")) IO.inspect(File.read("missing.txt")) map = %{a: 1} IO.inspect(Map.fetch(map, :a)) IO.inspect(Map.fetch(map, :b)) File.rm!("notes.txt")
elixir stdlib.exs
{:ok, "hi"}
{:error, :enoent}
{:ok, 1}
:error
:enoent is the Erlang atom for "no such file or directory", and it is the reason a caller branches on instead of a path. Map.fetch/2 answers a bare :error rather than a tuple, because a map lookup has nothing more to say; the with construct reads both shapes the same way.
The mistake: a pattern that assumes ok
The temptation is to match the success tuple and forget the other one. With a file that is there, the line works; with a file that is not, the match fails and the program stops with the tuple it got:
mistake.exs
{:ok, content} = File.read("missing.txt") IO.puts(content)
elixir mistake.exs
** (MatchError) no match of right hand side value:
{:error, :enoent}
mistake.exs:1: (file)
(elixir 1.19.7) lib/code.ex:1613: Code.require_file/2
The error is a MatchError and not a report about the missing file, which is why the pattern hurts: the reader has to decode :enoent from a failed match. The fixes are a case, a with, or the bang call File.read!/1, whose File.Error names the path and the reason in one line.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which two tuples does a function answer when it may fail?
Answer
{:ok, value} and {:error, reason}
The tag says which of the two shapes the caller got, and the second item carries the value or the reason.
-
What does the name ending in
!mean?Answer
the function raises instead of returning an error tuple
The pair version answers the error and the bang version raises it.
-
Why is the reason usually an atom?
Answer
because the caller decides how to report it
The function names the failure and the caller turns it into a message or a branch.
-
What does
Map.fetch/2answer for a missing key?Answer
:error
A map lookup has no more to say than that the key is absent, so the answer is the bare :error.
-
What does this program print?
defmodule D do def safe(a, b) when b != 0, do: {:ok, a / b} def safe(_a, 0), do: {:error, :zero} end IO.inspect(D.safe(8, 2))Answer
{:ok, 4.0}
The division of two integers gives a float, and the answer is the ok tuple.
-
What does this program print?
defmodule D do def safe(a, b) when b != 0, do: {:ok, a / b} def safe(_a, 0), do: {:error, :zero} end IO.inspect(D.safe(8, 0))Answer
{:error, :zero}
The second clause matches the zero and answers the error tuple rather than dividing.
-
What does this program print?
case File.read("missing.txt") do {:ok, text} -> IO.puts(text) {:error, reason} -> IO.puts("error #{reason}") endAnswer
error enoent
The file is absent, so the second clause prints the reason of the error tuple.
-
What does this program print?
IO.inspect(Map.fetch(%{a: 1}, :a))Answer
{:ok, 1}
fetch answers the ok tuple with the value when the key is there.
-
What does this program do?
{:ok, content} = File.read("missing.txt") IO.puts(content)Answer
A MatchError, because the value is an error tuple and the pattern asks for ok
The pattern matches only the ok tuple, so the error tuple fails the match and the program stops.
-
What does
File.read!/1do with a missing file?Answer
raises a File.Error that names the path and the reason
The bang version raises, and its exception is the File.Error a reader can act on.
Article author: Arthur Isaev