yourpalal

yourpalal

With/1 design patterns

When using with/1 to handle a bunch of matches and things that return {:ok, _} or :error or {:error, _} I often need to differentiate between errors, and I’ll wrap the individual matches in tuples, like this:

with(  
  {{:ok, shoes}, _} <- {get_shoes(outfit), :shoes},
  {{:ok, shirt}, _} <- {get_shirt(outfit), :shirt},
  {true, _} <- {shoes_match_shirt?(shoes, shirt), :matching}
) do
  {:ok, "service allowed"}
else
  {error, :shoes} ->
    {:error, "you forgot your shoes!"}
  _ ->
    :error
end

Mainly, I’m just curious how other people are handling things like this! What are you doing when you need to handle multiple error cases from with/1 ? One obvious solution is to give up on with/1 and use if or regular case statements or something like that.

Second, I’m open to any suggestions/criticism of the above code style.

Most Liked

hlx

hlx

I think you’re better of returning a more meaningful error from get_shoes/1

Example

{:error, {ShoesNotFound, "you forgot your shoes!"}}

# or

{:error, %ShoesNotFound{message: "you forgot your shoes!"}}
peerreynders

peerreynders

instead of Map.fetch(params, :shoes)

design patterns

Following Scott Wlaschin’s guidance - use functions!

def fetch_item(map, key) do
  case Map.fetch(map, key) do
    :error ->
      {:error, key}
    result ->
      result
  end
end

  ...

  with(  
    {:ok, shoes} <- fetch_item(outfit, :shoes),
    {:ok, shirt} <- fetch_item(outfit, :shirt),
    {true, _} <- {shoes_match_shirt?(shoes, shirt), :matching}
  ) do
    {:ok, "service allowed"}
  else
    {:error, :shoes} ->
      {:error, "you forgot your shoes!"}
    _ ->
      :error
  end

  ...

or

def fetch_item(map, key, msg) when is_binary(msg) do
  case Map.fetch(map, key) do
    :error ->
      {:error, msg}
    result ->
      result
  end
end

  ...

  with(  
    {:ok, shoes} <- fetch_item(outfit, :shoes, "you forgot your shoes!"),
    {:ok, shirt} <- fetch_item(outfit, :shirt, "you forgot your shirt!"),
    {true, _} <- {shoes_match_shirt?(shoes, shirt), :matching}
  ) do
    {:ok, "service allowed"}
  else
    {:error, msg} = msg_error when is_binary(msg) ->
      msg_error
    _ ->
      :error
  end

  ...
peerreynders

peerreynders

The idiom is {:ok, value}, {:error, reason}

So the pattern match should focus on the contents of reason.

For example:

Process.monitor/1 will result in a general message of the format:

{:DOWN, ref, :process, object, reason}

where reason can take on values like :normal, :noproc or :noconnection, i.e. values that are highly distinct and imply their context. So it’s a good idea to follow the same practice with {:error, reason} tuples.

Where Next?

Popular in Questions Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
chokchit
** (DBConnection.ConnectionError) connection not available and request was dropped from queue after 2733ms. You can configure how long re...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: The documentation above suggests that while ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
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

Other popular topics Top

axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48475 226
New
vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 31194 112
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 52774 488
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54250 245
New

We're in Beta

About us Mission Statement