purplesquirrel

purplesquirrel

Error handling with try/rescue vs with

I have a function work that get’s a record, requests data from a remote api and updates that record or returns some error tuples.

It’s possible for the DB record get to fail if the id is invalid and unsure what the generally preferred way of handling that kind of error is.

Personally I prefer option 2, but I worry about its limitations as described below.

Option 1

try/rescue first, case-match no the result of that, nest the with. Seems reasonable if a little verbose? Perhaps there is a nicer way to tie the try result with the case statement? This style reads ok here, but falls down when the with content is actually fairly long.

def work(id) do
  fruit = try do
    # will raise on bad id
    Fruits.get_fruit!(id)
  rescue
    Ecto.NoResultsError ->
      {:error, :invalid_fruit_id}
  end
  
  case fruit do
    {:error, e} -> {:error, e}
    fruit ->
      with {:ok, taste} <- TastesAPi.get_taste_for_fruit(fruit.name) do
        {:ok, fruit} = Fruit.update_fruit(fruit, %{taste: taste})
      else
        {:error, 404} -> {:error, :no_taste_for_fruit}
        {:error, :rate_limit} -> {:error, :api_rate_limited}
      end      
  end
end

Option 2

Move everything into a with, use a method that wont raise, check for nil instead.
It’s nicer to read, but how would you handle two functions that might return nil and want to return a different error depending on which failed? (Imagine you had Fruits.get_fruit_or_nil along with Mouth.get_mouth_or_nil and wanted to return :invalid_fruit_id or :invalid_mouth_id) Maybe if your handling is that complex it’s just an indication that you need more than a compressed with – returning to option 1?

def work(id) do

  with fruit when not is_nil(fruit) <- Fruits.get_fruit_or_nil(id),
       {:ok, taste} <- TastesAPI.get_taste_for_fruit(fruit.name)
  do
    {:ok, fruit} = Fruit.update_fruit(fruit, %{taste: taste})
  else
    nil -> {:error, :invalid_fruit_id}
    {:error, 404} -> {:error, :no_taste_for_fruit}
    {:error, :rate_limit} -> {:error, :api_rate_limited}
  end
end

Option 3

try/rescue with a throw. Not great, means you have to wrap your caller in try/catch. Seems like a worse version of option 1 by all metrics.

def work(id) do
  fruit = try do
    # will raise on bad id
    Fruits.get_fruit!(id)
  rescue
    Ecto.NoResultsError ->
      # use throw to 'return' early.
      throw {:error, :invalid_fruit_id}
  end
  
  with {:ok, taste} <- TastesAPi.get_taste_for_fruit(fruit.name)
  do
    {:ok, fruit} = Fruit.update_fruit(fruit, %{taste: taste})
  else
    nil -> {:error, :inavlid_fruit_id}
    {:error, 404} -> {:error, :no_taste_for_fruit}
    {:error, :rate_limit} -> {:error, :api_rate_limited}
  end
end

Marked As Solved

OvermindDL1

OvermindDL1

I just tag them:

with(
  ...
  {:a, a} <- {:a, do_something()},
  {:b, b} <- {:b, do_something_else(a)},
  ...
do
  ...
else
  ...
  {:a, err} -> ...
  {:b, err} -> ...
  ...
end

The happy_path library (precursor to Elixir getting with) used @tagname to do quick-tags like that, it was very convenient.

Also Liked

purplesquirrel

purplesquirrel

Ah of course, fantastic.

Where Next?

Popular in Questions Top

pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
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
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
New

Other popular topics Top

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
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
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
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 45766 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
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
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
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
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
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New

We're in Beta

About us Mission Statement