Best Practises for Error handling elixir?

How to handle excepions in elixir?
Suppose i have A, B, C ,D, E modules. and each module has get() function.
A.get() method will call the B.get() method.
B.get() method will call the C.get() method like D.get() method will call the E.get() method for some calculations.
suppose if i am gettting an error in E.get() method then thow to pass that error too A.get() method.
i need best practises for this case.
is it need to catching the error in all the modules and and re throwing to parent module?

1 Like

It’s hard to be specific without knowing your exact use case, but since Elixir code run in processes, the most natural way to handle it is don’t. Let it crash, and let the monitoring process (Supervisor) restarts it. Catching exceptions (using try and rescue) is quite frowned upon I think.

However, it really depends on the nature of the error. Is it often or rare? Is it caused by misbehavior of the outside world, eg. network or hardware fails? The information could help to determine whether or not you need to write code to handle it.

1 Like

You may want to consider if you really need to catch exceptions. For certain things you may simply want to spin up a new process and let a supervisor handle any failure in it (by restarting the process, as one example).

A common pattern in this case is to have a get/x and a get!/x function (where x is the arity).

The unbanged version does return a tuple which first element is either :ok or :error while the second element is the result of the computation or the reason of failure (atom or string) depending on the first tuple.

The banged version on the other hand does either return the result of the computation or raises an exeption.

You can observe this pattern very often in the elixir standard library very often, an example of this is Map.fetch/2 and Map.fetch!/2.

The banged version is very often a simple wrapper around the unbanged one as in the following example:

@spec foo(any) :: {:ok, Foo.t} | {:error, String.t}
def foo(bar), do: bar |> do_the_magic

@spec foo!(any) :: Foo.t | no_return
def foo!(bar) do
  case foo(bar) do
    {:ok, result} -> result
    {:error, _}   -> raise FooError

In the context of well designed supervision trees you probably do not even need to catch something raised, as well as you probably do not need to handle {:error, _} cases. Just try to match-assign the {:ok, _} and let the process die when it failed.

In the case you really have to handle the errors because of reasons that matter, do not raise, but use signaling tuples as in the unbanged functions, thrown axceptions do add some overhead and do add a significant runtime-cost.

Exceptions are to see exactly as this! An exception, a thing that might happen, but you do not consider it under normal circumstances. Use them only if you really want to fail, do not try to recover from them!


If only match return value with {:ok, _} and it failed, we will got an error message that match failed, which is not exactly right.

It’s more concise to have error message that tell us what exactly error is rather than find that error with match error. This somehow means, we still need to match the {:error, _} pattern and do some logging etc. Any idea to remove this complexity?

Generally it is exactly right. You should only handle returns from a function which you actually can handle. Please don’t program defensively.

You can see {:ok, res} = my_fun() as an assertion which should never fail. (or a failure you can’t do anything about anyway). And if it does fail, the supervisors make sure your application doesn’t crash.

If {error, reason} is something you need to handle in your business logic you deal with it with pattern matching and you should only deal with the errors you care about. Because it is part of business logic you have to deal with is so the “complexity” is unavoidable.

Don’t catch errors and log anywhere except the top level of your code. It is better to bubble up. Error messages should ideally be tuples of atoms with as much information as possible so that you clearly know which sort of errors to handle and which to ignore.

A nice “pattern” in erlang applications is to return atoms {:error, :some_error} and then have the module returning the error being able to format it into a readable string. This means you can bubble up the error message as a tuple and only the code doing the logging translate it to human readable format. It also means the module producing the error is able to give a meaningful message rather than the caller having to make something up.

case MyModule.my_fun() do
  {:ok, res} -> :working_good
  {:error, :some_error} -> {:error, :some_error}

and in top level handling code:

case x of
  {:error, reason} -> Logger.log(MyModule.format_error(reason))

Thanks @cmkarlsson, your answer helps a lot.

I’m going to conclude that

  • error should be returned as {:error, error} tuple
  • error should raise via pattern matching
  • error should be reported and formatted at top level via bubble up

As an aside, if I get an exception from something else then I’ll bubble it up by ‘returning’ the exception (not raising) so I can handle it better. The exceptional library normalize takes anything and returns either a value or an error as appropriate for the passed in input. That library is quite convenient and I’ve used it all over the place to significantly reduce my amount of code to only the important bits. :slight_smile:

From Phoenix 1.3 action_fallback with proper Controller to handle errors will do the same. Maybe next step would be doing similar thing for handle errors on channels, but certainly handling errors there is bit more complex regarding how we would like to notify clients about the error.

Thanks Guys.

May be catching exceptions and re throwing works in object oriented programming language.
But in functional programming language, especially Elixir, May be we have to catch the error when its fails and return the error tuple like ({:error, error_message}). then we have to match this value in parent calls.