tomekowal

tomekowal

Easiest way to find the function that didn't match in the `with` statement

I have code like this (but bigger)

defmodule WithStacktrace do
  def hello do
    with {:ok, _value} <- {:ok, 1},
      {:ok, value} <- :wrong_shape do
      {:ok, value}
    else
      {:error, e} -> {:error, e}
    end
  end
end

This will raise:

** (WithClauseError) no with clause matching: :wrong_shape
    (with_stacktrace 0.1.0) lib/with_stacktrace.ex:3: WithStacktrace.hello/0

So, the stack trace points to the beginning of the with statement (line 3).
But the expression that matches neither its success case nor else block is at line 4 {:ok, value} <- :wrong_shape.

Let’s say my with expression consists of 10 such calls. How can I easiest check which one returns the :wrong_shape?

I am currently adding IO.inspects after each of those statements :smiley:

Marked As Solved

kartheek

kartheek

You can run debug session - if you can replicate the error.

Also if your code is not confirming to type spec - won’t the code analysis tools catch this ?

Also Liked

Nicd

Nicd

A couple of ideas.

Sometimes I’ve used tagged tuples. Something like:

with {:part1, {:ok, data}} <- {:part1, get_data()},
  {:part2, :ok} <- {:part2, process_data()} do

This allows matching the failed value in else and would show up in the WithClauseError too. But this can get very noisy very quickly.

Another option is to use a helper module like this (from ihumanable/icecreamcohen on Discord):

defmodule WithHelper do
  @spec op(atom(), any(), :strict | :permissive) :: any()
  def op(label, thing, mode \\ :strict) do
    if mode == :permissive do
      opt_permissive(label, thing)
    else
      op_strict(label, thing)
    end
  end

  defp opt_permissive(label, err) when err in [:error, false, nil], do: {label, err}
  defp opt_permissive(label, {:error, _} = err), do: {label, err}
  defp opt_permissive(_label, val), do: val

  defp op_strict(_label, val) when val in [:ok, true], do: val
  defp op_strict(_label, {:ok, _} = success), do: success
  defp op_strict(label, other), do: {label, other}
end

And now we can do it like this:

with {:ok, data} <- op(:part1, get_data()),
  :ok <- op(:part2, process_data()) do
    ...
else
  {:part1, error} -> do_something(error)
  {:part2, _error} -> halt()
end

This lessens the noise somewhat, assuming your functions stick to the ok-tuple standard.

tomekowal

tomekowal

I agree with Crhis but I think I wasn’t clear with my question.

I don’t want to identify failing cases because I want to handle them differently.

In my scenario all functions should return {:ok, value} or {:error, reason} and that else clause is irrelevant.

But one of the functions does not conform to specification and returns something different which I’d like to fix. I encounter that scenario fairly often and each time it is a pain :stuck_out_tongue:

kartheek

kartheek

Relevant thread about with statements.

https://medium.com/very-big-things/towards-maintainable-elixir-the-anatomy-of-a-core-module-b7372009ca6d

Look at With chaining section of Sasa Juric article (I am unable to provide link to section as it has no hyperlink)

Kernel.SpecialForms — Elixir v1.16.0 - this is from elixir docs explain about else in with .

I am convinced with statements don’t need else most of the time. Are you trying to do some error recovery from else ?

if you have only one clause in else pattern matching error with {:error, e} and returning same, then its not needed. with will return error directly without need of else. I realised it very recently.

tomekowal

tomekowal

Thanks for your answer!

I am doing debugging and I see that one of my functions does not conform to the expected spec. E.g. it might return just :error instead of {:error, reason} or just an atom e.g. :invalid_credentials instead of {:error, :invalid_credentials}.

Adding an else clause helps a little because I don’t pass that unexpected thing further down the line. But I think that is irrelevant. If I don’t have the else block, the entire with statement returns :wrong_shape and I am still back at square one.

How can I quickly discover which one of with statements did not match first?
I wish WithClauseError reported first expression that did not match instead of the line where the with keyword is :slight_smile:

tomekowal

tomekowal

Debugging session is the way to go! Thank you!

I’ve never used it before and it looks awesome.

We are trying to introduce dialyzer right now, so things are still rough around the edges :slight_smile:

Where Next?

Popular in Questions Top

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
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
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
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
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
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

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
Tee
can someone please explain to me how Enum.reduce works with maps
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
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 35421 110
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
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
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
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
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
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

We're in Beta

About us Mission Statement