intercaetera

intercaetera

Error handling with "with"

Sort of a newbie code review question, but I’m curious if there’s a way to work around this. I’m still trying to wrap my head around good practices for error tuples. The precise code is in a Phoenix app but it could well exist outside of it. I have three functions in three modules:

# TaskRegistry
  def get_status(id) do
    with [{id, status}] <- :ets.lookup(:task_registry, id)
    do
      {:ok, {id, status}}
    else
      [] -> {:error, :file_not_found}
      _ -> {:error, :unknown}
    end
  end

  # TaskServer
  def handle_call({:status, id}, _, state) do
    with {:ok, {_, status}} <- TaskRegistry.get_status(id)
    do
      {:reply, {:ok, status}, state}
    else
      error -> {:reply, error, state}
    end
  end

  # TaskController
  def status(%Plug.Conn{path_params: %{"id" => id}} = conn, _params) do
    with {:ok, status} <- TaskServer.status(id)
    do
      json(conn, %{status: status})
    else
      {:error, :file_not_found} -> conn |> put_status(404) |> json(%{status: "not found"})
    end
  end

This doesn’t really seem right to me, that each of these has a with clause. But without it on each failed request the TaskServer crashes (and Phoenix returns HTTP 500, which is undesirable but not really relevant to the question). It doesn’t seem right that the GenServer should crash just because someone put in something wrong. I’m not sure how to refactor this well, though.

Most Liked

stefanchrobot

stefanchrobot

All these functions would be much better off with case instead of with. Avoid else in with is a pretty good advice.

al2o3cr

al2o3cr

It’s hard to say exactly what causes this crash without the code, but I’d guess it’s a MatchError when using code like the above but without with, turning <- to =

For an expression with one statement in the “happy path” of a with, case will be more readable:

  def get_status(id) do
    case :ets.lookup(:task_registry, id) do
      [{id, status}] -> {:ok, {id, status}}
      [] -> {:error, :file_not_found}
      _ -> {:error, :unknown}
    end
  end

Where Next?

Popular in Questions Top

Fl4m3Ph03n1x
Background Let’s assume I have a typical GenServer that receives messages as requests, does some operation in a DB and returns responses....
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
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
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
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
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
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
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 49522 488
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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement