[erlang-questions] An Erlang 101 question

Martin Karlsson martink@REDACTED
Thu Jul 16 23:44:41 CEST 2015

It boils down to what the caller wants to do with the result and if it
makes sense to handle it at all.

For database stuff I usually do:
{ok, Result} = query().

and return something else for errors, or others, such as:

{error, not_found} = query().

This way those who don't care about stuff going wrong do:
{ok, Result} = query().
knowing that Result will always contain something useful.

And those who do care:

case query() of
  {ok, Result} -> 'hello world!'.
  {error, not_found} -> ooops

If you expect your queries to always success (i.e the errors are not
part of the normal flow) you can even throw on errors and just return
the result.

Result = query()

and if you need to check it:

try query() of
   Result -> Result
    {throw, not_found} -> oops

Your current case is just a variant of the first option but with less
information. It is harder to pattern match meaning you'd basically
always need:

case query() of
   [] -> not_found;
   Result -> 'hello world!'

mnesia is a funny application which uses both of the above approaches
depending on if you are using mnesia:transaction (returns {atomic,
Result} or {aborted, Reason}}) vs mnesia:activity which throws on

More information about the erlang-questions mailing list