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?

Where Next?

Popular in Questions Top

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
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
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 t...
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
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
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&amp;query=perfume&amp;page=2, I would like to get: ...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
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
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

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 52774 488
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
jononomo
For some reason my phoenix channels are working for me in my local dev environment, but as soon as I deploy via Docker, I get a 403 error...
New
greenz1
I have a phoenix application from which a user can download multiple(5-6) files of size 1MB. I couldn’t find anything related to sending ...
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
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
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
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement