Wrap your return values in tuples so you can clearly match them in the else block

The with expression allows us to declare clauses and their expected results. The clauses are executed in order until the end of the list, or until one clause doesn’t match with its expected result. Here is the example from the Elixir documentation:

A simple `with` expression

In this example, we are calculating the area of a rectangle. If everything works out we will return {:ok, area} , if not, we will fall through to the else block and return the error tuple {:error, :wrong_data} .

But what happens if we want to send back a better error message? Right now we fall through to the else block with an :error atom that is returned from Map.fetch/2 , but we don’t now which clause it came from (was the :width missing? or was the :height missing?).

To know which clause is failing, we can wrap each side in a tuple that describes the clause, and then match in the else block:

A `with` expression with improved error responses via tuple-wrapping

This “tuple-wrapping” technique borders on the functional programming concept of “Monads”, but is not something I am going to be discussing here.