alexandrubagu

alexandrubagu

Handle_info when using Task.Supervisor.async_nolink

Hi,

I want to handle the following exit example ( String.to_integer(input) is jus an example and can be replaced with raise). This happen when I call My.GenServer.some_method(My.GenServer, "test"). I will be grateful if someone has a suggestion for this.

10:26:42.321 [error] GenServer My.GenServer terminating
** (stop) exited in: Task.await(%Task{owner: #PID<0.124.0>, pid: #PID<0.128.0>, ref: #Reference<0.4181578440.4035444737.94083>}, 5000)
    ** (EXIT) an exception was raised:
        ** (ArgumentError) argument error
            :erlang.binary_to_integer("test")

Here’s the code:

defmodule My.Application do
  use Application

  def start(_type, _args) do
    import Supervisor.Spec, warn: false

    children = [
      worker(My.GenServer, []),
      supervisor(Task.Supervisor, [[name: My.Task.Supervisor, restart: :transient]]),
    ]
    
    opts = [strategy: :one_for_one, name: Test.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

defmodule My.GenServer do
    def start_link do
      GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
    end

    def init(:ok) do
      # Process.flag(:trap_exit, true)
      {:ok, []}
    end

    def some_method(pid, input) do
        GenServer.call(pid, {:some_method, input})
    end

    def handle_call({:some_method, input}, _from, state) do
      # because we don't want to terminate GenServer use Task.async_nolink
      task = Task.Supervisor.async_nolink(My.Task.Supervisor, fn ->
          # raise argument error when passing binary
          String.to_integer(input)
      end)
      {:reply, Task.await(task), state}
    end

    def handle_info({:EXIT, from, reason}, state) do
      IO.inspect "handle_info::exit"
      IO.inspect reason
      {:noreply, state}
    end

    def handle_info({_ref, result}, state) do
      IO.inspect "handle_info::result"
      IO.inspect result
      {:noreply, state}
    end

    def handle_info({:DOWN, _ref, :process, _pid, reason}, state) do
      IO.inspect "handle_info::down"
      IO.inspect reason
      {:noreply, state}
    end

    def handle_info(msg, state) do
      IO.inspect "handle_info"
      IO.inspect msg
      {:noreply, state}
    end
end

I’ve read the docs from here regarding Task.Supervisor.async_link: if you create a task using async_nolink inside an OTP behaviour like GenServer, you should match on the message coming from the task inside your GenServer.handle_info/2 callback.

My problem is that handle_info is not called, I try to debug using observer attaching a trace to My.GenServer and I see that My.GenServer is receiving a :DOWN message:

Any solution to this problem ?
Thanks

Most Liked

NobbZ

NobbZ

When using Task.await/1 it will handle the :DOWN-message from the Task. It will handle it by calling exit/1. So the GenServer will be exited because of that.

If you want to be more failsafe, you have to do the waiting for the result and the :DOWN-message completely on your own.

dom

dom

Oh, I see what you mean. Instead of using await you can store the task’s ref and the caller in your GenServer state, then use GenServer.reply in your handle_info to send back the response to the caller.

NobbZ

NobbZ

As it is now you gain nothing from the Task except for the timeout, you could do the work in the GenServer directly and it wouldn’t matter (as long as no timout would happen in the Task)

The more correct way were to put the returned task into your state, alongside the from and return a :noreturn tuple in handle_call/3.

Some time later you will receive a message with either the result of the computation done in the Task, which you then can GenServer(from, answer) to your caller.

Or you might receive a :DOWN, which you will need to find ways to tell your caller about. Most idiomatic way were to use an :error-tuple I think.

Where Next?

Popular in Questions Top

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
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
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
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
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

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
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 records...
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

We're in Beta

About us Mission Statement