aratz-lasa
How to format return values
I have searched, but I have not found it. If it is a duplicated question I am so sorry.
I want to know how and when to format the returned values in a function. Because a lot of times, it is returned {:ok, value} and others just value . So, when should I use the status along the value?
Most Liked Responses
kokolegorille
Often functions ending with ! will return the value, or raise an error.
While those without ! at the end return {:ok, value} | {:error, reason}
tty
From laziness we treat value as {:ok, value} but if value is an error code then it should be {:error, value}.
A status should be descriptive and makes sense for the callee when pattern matching.
E.g. if a function spec is
{:ok, :connected} | {:ok, :received} | {:error, error_code} it can easily be changed to :connected | :received | {:error, error_code} without losing information.
tme_317
I’d say #2 is the good choice since it’s much more idiomatic and found throughout the ecosystem for functions that can fail. And as @kokolegorille said earlier naming the function with a bang (i.e. func!()) if the function raises instead of returning an error tuple.
That said occasionally I find something like Integer.parse/2 in the stdlib can return {42, ""} or :error. Or Repo.get/3 from Ecto which returns %Struct{...} or nil if the query returns 0 rows. I guess the idea if there are no records it is not an error condition and should return the concept of nothing which is nil or [] for a list of nothing.








