Stop process in case of failure or invalid data

Asked

Viewed 27 times

1

I am developing an elixir API and I have a certain process that performs 6 chain actions. My question is how to interrupt this execution each of these 6 actions has a problem.

I would not like to cascade into several case blocks.

Comparing with OO I would like a Return.

Someone has a good solution for this?

1 answer

0


In the functional paradigm, by the concept of purism, you don’t use exceptions for flow control. That’s why many functions return a tuple {:ok, _} or {:error, _}, or simply :ok and :error.

To check the return of multiple calls, avoiding chains of if, the clause is used with. An example:

with {:ok, %{id: external_id}} <- Parser.parse_body(body),
     {:ok, tweet} <- TwitterApi.get(external_id),
     {:ok, message} <- Messaging.create_message(tweet) do
  respond_with_status(200)
else
  {:error, cause} -> respond_with_status(400)
  :error -> respond_with_status(502)
end

Browser other questions tagged

You are not signed in. Login or sign up in order to post.