jonathan-scholbach

jonathan-scholbach

Avoiding long `with` blocks

I find myself using a lot of very long with-statements. The functions in the with pipeline return {:ok, result} or some {:error, :error_type, additional_error_information} It could look somewhat like this:

with \
   {:ok, result_a} <- function_a(input),
   {:ok, result_b} <- function_b(result_a),
   {:ok, result_c} <- function_c(result_b),
   :ok <- some_validation_function_d(result_c)
do
  {:ok, result_c}
else
  {:error, :error_in_a} -> {:error, :internal_error}
  {:error, :another_error_in_a} -> {:error, :some_other_error}
  {:error, :error_in_b} -> {:error, :strange_error}
  {:error, :error_in_b, msg} -> {:error, :strange_error, msg}
  {:error, :error_in_c, msg} -> {:error, :internal_error}
  {:error, :validation_error, _msg} -> {:error, :validation_error, input, msg}
end

But sometimes I have blocks that are way longer even.

This looks like a legacy of thinking like an imperative programmer to me, using a a (not so) nicely nested catch-try tree.

I would like to find a way to make my pipeline functions perform an “early return”, so I would like to “break” the pipeline.

It should look something like this instead (not working pseudocode following):

input
|> {function_a(), error_handler_a}
|> {function_b(), error_handler_b}
|> {function_c(), error_handler_c}
|> {function_d(), error_handler_d}

Where each error_handler maps the error from the function to the correct error return I am using in this context. How do I do this best? I would be willing to write a macro (although I have no experience with this.) Another constraint: I do not want to use an external dependency for this, but be in full control of the code myself.

I am new to Elixir, and I can imagine that my idea of a solution does not make too much sense. If this is the case, what are other best practices to avoid the problem in the first place?

Most Liked

stefanchrobot

stefanchrobot

One way to approach this is to avoid the else clause in with. This means that you need to introduce a somewhat generic error struct - it can be app-wide, or specific to some context. All the smaller functions will need to return the error struct on error or you’ll need to write local wrappers around them. So it would be something like this:

# Generic error.
defmodule MyApp.Error do
  defexception [:code, :message, :meta]

  @impl Exception
  def message(%__MODULE__{code: code, message: message, meta: meta}) do
    "Error (#{code}): #{message}, meta: #{inspect(meta)}"
  end

  def new(code, message, opts \\ []) do
    %__MODULE__{
      code: code,
      message: message,
      meta: opts[:meta] || %{}
    }
  end

  def auth_error() do
    new(:auth_error, "authorization error")
  end

  def validation_error(changeset) do
    new(:validation_error, "validation error", meta: changeset)
  end
end

# App logic.
defmodule MyApp.Foo do
  def bar(input) do
    with {:ok, result_a} <- function_a(input),
         {:ok, result_b} <- function_b(result_a),
         {:ok, result_c} <- function_c(result_b),
         :ok <- some_validation_function_d(result_c) do
      {:ok, result_c}
    end
  end

  # Example of wrapping.
  defp some_validation_function_d(result_c) do
    case run_validation(result_c) do
      :ok -> :ok
      {:error, changeset} -> {:error, MyApp.Error.validation_error(changeset)}
    end
  end
end

# Top-level code that runs the logic (e.g. controller, background job, etc.)
defmodule MyAppWeb.FooController do
  def create(conn, _params) do
    case MyApp.Foo.bar(params) do
      {:ok, result} -> #...
      {:error, %MyApp.Error{code: :validation_error}} -> # ...
    end
  end
end

See also Good and Bad Elixir.

As an added bonus, all the functions that return {:error, %MyApp.Error{}} now became nicely composable.

Where Next?

Popular in Questions Top

yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New

We're in Beta

About us Mission Statement