Kurisu

Kurisu

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…

Showing Posts 1 to 10

idi527

idi527

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

Kurisu

Kurisu OP

Ok that way I keep the current code, simple and short. I will just writte one more clause for the function that returns {:error2, message} for it takes one more parameter (conn) and just returns it with its own data.
Thank you ^^

ntalfer

ntalfer

I fell into a similar issue and I don’t want to create new functions that return wanted variables in function.
Let’s take this simple snippet:

iex(1)> with a <- 1,
...(1)> 2 <- 3 do
...(1)> :ok
...(1)> else error ->
...(1)> {:error, binding()}
...(1)> end
{:error, [error: 3]}

You can see that the"a" variable is not bound to the else block context, there’s only the “error” one.

If we go with the solution given in the previous comments, we have to introduce a function that returns “a” but you will easily agree that doing so for a such a simple piece of code is stupid:

iex(5)> f = fn(x) -> {3, x} end   
#Function<6.50752066/1 in :erl_eval.expr/5>
iex(6)> with a <- 1,           
...(6)> 2 <- f.(a) do
...(6)> :ok
...(6)> else error ->
...(6)> {:error, binding()}
...(6)> end
{:error, [error: {3, 1}, f: #Function<6.50752066/1 in :erl_eval.expr/5>]}

I found another solution by using process dictionary:

iex(1)> with a <- 1,  
...(1)> _ <- Process.put(:a, a), 
...(1)> 2 <- 3 do
...(1)> :ok
...(1)> else error ->
...(1)> {:error, error, Process.get(:a)}
...(1)> end
{:error, 3, 1}

…but I’m not 100% happy with it either.

Does anyone have a more elegant solution?

Thanks!

idi527

idi527

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

ntalfer

ntalfer

I don’t care about errors.
As in the original question, I would like to get all variables assigned in the first with clauses (before something went wrong) from the else block.

idi527

idi527

That means that you do care about errors and should look into using a case block instead of with.

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
Kurisu

Kurisu OP

Hum, very informative … ^^

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!

czrpb

czrpb

i too am a bit surprized the bindings in the do arent accessable in the else, given the my interpretation of the purpose of the with.

so .. is @ntalfer solution still the “best” one? the only other way ive found after a bit of research is to implement some sort of railway oriented version, which is certainly non-trivial just to get access to the bindings.

Where Next? Top

Trending in Questions Top

katta
I having some trouble figuring out if I have set myself too strict of standards for my production server. Currently I can handle 75% of r...
New
achenet
Hello, I’m trying to build a basic Phoenix web-app, and I’d like to use Tailwind. However, when I launch mix phx.server, I get an error...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
Cxx-mlr
I’m working on a small exercise involving update_in/3, and I came up with this solution: data = %{ name: "Periodic Table", category:...
New
ChrisAmelia
I’ve got trouble wrapping my head around the order in which functions are called in this snippet (from Phoenix’s authentication): toke...
New
dillonoconnor
Is there any way to avoid the Hologram compiler running when using iex? It seems like the front-end code could potentially be disregarded...
New
thiagogsr
** (ArgumentError) expected :max_attempts to be a positive integer, got: {:@, [line: 10, column: 19], [{:max_attempts, [line: 10, column:...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
budgie
A little off-topic, but I feel like people here have a good head on their shoulders. I used to be quite good at making software. Was luc...
New
KristerV
Hey. Is there anyone here who creates agents in their apps? Not talking about using agents, but creating them. I’m finding it pretty diff...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews