Raise or return an error
A function has two ways to say that it failed: it returns an ok or error tuple, or it raises. The rule that keeps a program readable in Elixir is about the boundary: a failure the caller can do something about is a value, a failure that means the program is wrong is an exception, and the second function of a library lets each caller choose which one it wants.
A library that answers with a pair
The store below answers {:ok, value} for a key it holds and {:error, :not_found} for one it does not. The atom says what happened and the caller decides what to print, what to retry, or whether to stop:
library.exs
defmodule Store do defmodule NotFoundError do defexception [:key] def message(%{key: key}), do: "no entry for #{inspect(key)}" end def find(entries, key) do case Map.fetch(entries, key) do {:ok, value} -> {:ok, value} :error -> {:error, :not_found} end end def find!(entries, key) do case find(entries, key) do {:ok, value} -> value {:error, :not_found} -> raise NotFoundError, key: key end end end entries = %{a: 1} IO.inspect(Store.find(entries, :a)) IO.inspect(Store.find(entries, :b)) IO.inspect(Store.find!(entries, :a))
elixir library.exs
{:ok, 1}
{:error, :not_found}
1
The exception type is declared inside the module that raises it, which is where its name belongs: Store.NotFoundError. It carries the key rather than a sentence, and its message/1 callback builds the sentence from the data, so a crash report names the key that was missing and the caller that catches the struct still has the key to work with.
The bang wrapper and its exception
find!/2 is six lines and no logic of its own: it calls the pair version, takes the value out of the ok tuple and raises on the error. That is the shape every bang function of the standard library has, and the reason it exists: the rule is written once, in the library, and each caller picks the line it wants.
Two callers, two choices
The caller that can continue reads the pair; the caller that cannot lets the exception stop it and catches it where the program reports. The same library serves both, and neither caller wraps a try around the call it did not need:
callers.exs
defmodule Store do defmodule NotFoundError do defexception [:key] def message(%{key: key}), do: "no entry for #{inspect(key)}" end def find(entries, key) do case Map.fetch(entries, key) do {:ok, value} -> {:ok, value} :error -> {:error, :not_found} end end def find!(entries, key) do case find(entries, key) do {:ok, value} -> value {:error, :not_found} -> raise NotFoundError, key: key end end end entries = %{a: 1} case Store.find(entries, :b) do {:ok, value} -> IO.puts(value) {:error, :not_found} -> IO.puts("no entry, using the default") end try do Store.find!(entries, :b) rescue e in Store.NotFoundError -> IO.puts("stopped: #{Exception.message(e)}") end
elixir callers.exs
no entry, using the default
stopped: no entry for :b
The second caller uses Exception.message/1 rather than a field, because the sentence is the work of the callback and not a field of the struct. The exceptions lesson covers the clauses that catch a type; here the point is who decides to fail, and the answer is the caller.
A boundary that validates
A value that arrives from outside the program is checked where it enters, and the check answers a pair like every other expected failure. The port below is valid only inside the range a TCP port allows, and the guard makes that the definition of a good value:
validate.exs
defmodule Parse do def port(text) do case Integer.parse(text) do {number, ""} when number in 1..65_535 -> {:ok, number} _ -> {:error, :bad_port} end end end IO.inspect(Parse.port("8080")) IO.inspect(Parse.port("70000")) IO.inspect(Parse.port("x"))
elixir validate.exs
{:ok, 8080}
{:error, :bad_port}
{:error, :bad_port}
A failure of this check is expected: a user types a wrong port, a file holds a wrong value, and the program answers with a message rather than a stack. A bug inside the function, such as a call on the wrong value, is the other kind and is left to crash. The two are told apart by where the value came from, not by how the code is written.
The mistake: a function that raises for an expected failure
A library whose plain function raises forces every caller to wrap it, and a missing key is not a bug in the caller. The module below answers with Map.fetch!/2, so a key the caller expected to be absent stops the program:
mistake.exs
defmodule Store do def find(entries, key), do: Map.fetch!(entries, key) end Store.find(%{a: 1}, :b)
elixir mistake.exs
** (KeyError) key :b not found in:
%{a: 1}
:erlang.map_get(:b, %{a: 1})
mistake.exs:2: Store.find/2
mistake.exs:5: (file)
The report is a KeyError from inside the library, and the caller learns that a key may be missing only by reading the source or the report. The fix is the pair version and a bang version beside it, which is the shape the lesson opened with: the library decides what the failure means, and the caller decides whether it stops.
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.
-
When should a library answer an error tuple rather than raise?
Answer
when the failure is expected and the caller can handle it
An expected failure is a value the caller branches on; a bug is left to crash.
-
What does a function whose name ends in
!do with an error tuple?Answer
raises the reason as an exception
The bang version takes the value out of the ok tuple and raises on the error.
-
Where is the sentence of a custom exception built?
Answer
in the message/1 callback of the exception module
The callback builds the text from the fields, which is why Exception.message/1 is used.
-
What tells an expected failure from a bug?
Answer
where the value came from: outside the program or from the code
A value from a user or a file is checked; a value the code built wrongly is a bug.
-
What does this program print?
defmodule S do def find(entries, key) do case Map.fetch(entries, key) do {:ok, value} -> {:ok, value} :error -> {:error, :not_found} end end end IO.inspect(S.find(%{a: 1}, :b))Answer
{:error, :not_found}
The map does not hold the key, and the case answers the error tuple.
-
What does this program print?
defmodule S do def find(entries, key) do case Map.fetch(entries, key) do {:ok, value} -> {:ok, value} :error -> {:error, :not_found} end end end IO.inspect(S.find(%{a: 1}, :a))Answer
{:ok, 1}
The key is there, so the answer is the ok tuple with the value.
-
What does this program print?
defmodule S do def find(entries, key), do: Map.fetch!(entries, key) end IO.inspect(S.find(%{a: 1}, :a))Answer
1
fetch! answers the value itself when the key is there.
-
What does this program do?
defmodule S do def find(entries, key), do: Map.fetch!(entries, key) end S.find(%{a: 1}, :b)Answer
A KeyError, from inside the library, for a failure the caller expected
The bang call raises, and the caller gets a crash instead of a value it could handle.
-
What does
Exception.message/1answer for a stored error?Answer
the sentence built by the message callback
The call asks the exception for its message, which the callback builds from the fields.
-
Why does a boundary validate instead of raising?
Answer
because the value comes from outside and a wrong one is expected
A value a user typed may be wrong, so the program answers a message rather than a crash.
Article author: Arthur Isaev