Kurisu

Kurisu

How can I access variable defined in "With" statement from its "else" block?

Hello forum!
I’m trying to retrieve an updated conn, returned in the first line of a “with” statement, when second line failed. But I’m getting some error that says new_conn variable doesn’t exist. In the “do” block it is fine though.
Let me show you what my code looks like:

def some_action(conn, params) do
    with {:ok1, some_result, new_conn} <- some_func(conn, params),
      {:ok2, another_result} <- another_func(some_result)
    do
      new_conn |> redirect(to: some_path(conn, :index)) # new_conn is accessible here
    else
      {:error1, message} -> render(conn, "some_error_template.html")
      # new_conn is not accessible here
      {:error2, message} -> render(new_conn, "other_error_template.html")
    end
 end

Please how do you think I could get new_conn in the “else” block?

I have an idea but I’m wondering if it is not bad to use a function such as Tuple.append/2 to ensure the new_conn is present in the matching tuple…

Marked As Solved

peerreynders

peerreynders

You don’t.

You probably ran into this:

You’re building values.

So

iex(1)> fun = fn () ->
...(1)>   with a <- 1,
...(1)>        {2,_} <- {3,a} do
...(1)>     :ok
...(1)>   else
...(1)>     {_,a} = error ->
...(1)>       {:error, error, a}
...(1)>     error ->
...(1)>       {:error, error}
...(1)>   end
...(1)> end
#Function<20.127694169/0 in :erl_eval.expr/5>
iex(2)> fun.()
{:error, {3, 1}, 1}
iex(3)>

So you just have to build the value that contains all the information that you need for the error.

The code in the OP would then look something like this:

def some_action(conn, params) do
    with {:ok1, some_result, new_conn} <- some_func(conn, params),
      {{:ok2, another_result},_} <- {another_func(some_result), new_conn}
    do
      new_conn |> redirect(to: some_path(conn, :index)) # new_conn is accessible here
    else
      {:error1, message} -> render(conn, "some_error_template.html")
      {{:error2, message}, new_conn} -> render(new_conn, "other_error_template.html")
    end
 end

Also Liked

ntalfer

ntalfer

thanks @peerreynders

based on this thread, I ended by creating a kind of accumulator that gathers all results got during the multiple clauses

this more generic solution looks like:

with {{:ok, res1}, acc} <- {fun1(), []},
     {{:ok, res2}, acc} <- {fun2(), acc ++ [res1]},
     ...
     {{:ok, resN}, acc} <- {funN(), acc ++ [resN-1]} do
      # do some stuff...
else 
    {error, acc} ->
     # error contains the result of funP
     # acc contains the results of fun1 to funP-1
     # do some other stuff...
end

thanks!

idi527

idi527

You can return {:error, conn, message} from your functions.

idi527

idi527

If you care about errors, maybe try using a case block?

al2o3cr

al2o3cr

The issue is scoping: in the example above, what is res4 bound to when fun2() returns {:error, :nope}?

AFAIK, Elixir expects to be able to determine which bindings are in scope at each point statically at compile-time.

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
LegitStack
I’m hoping you guys can give me some general advice and perhaps code examples if you’re feeling up to it. I’m very interested in Elixir,...
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
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
tduccuong
Hi, is there any work on GUI with Elixir, that is similar to Electron/Javascript? My idea is to bundle Phoenix and BEAM into a single se...
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
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
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
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
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

TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
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
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
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
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
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
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
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
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement