GenServer error getting: no process: the process is not alive

Hi all ;),

I followed the guide on Elixir’s getting started coupled with the GenServer in hexdocs and another tutorial to create a simple cache GenServer.

Something, probably simple, evade me and it seems the server is not started, yet it is in the child array for supervision in the application.ex.

Here’s the code for the GenServer:

defmodule Tangara.Cache do
  use GenServer

  def start_link(_opts) do
    IO.puts("start_link called")
    GenServer.start_link(Tangara.Cache, [])
  end

  def get_countries do
    get("countries")
  end

  def get(key) do
    case GenServer.call(Tangara.Cache, {:get, key}) do
      nil -> []
      x -> x
    end
  end

  @impl true
  def init(_opts) do
    IO.puts("init called")

    {:ok, json} = File.read("priv/countries.json")
    countries = Jason.decode!(json)

    {:ok, %{"countries" => countries}}
  end

  @impl true
  def handle_call({:get, key}, _from, map) do
    {:reply, Map.get(map, key), map}
  end
end

I’ve added IO.puts as desperation. Here’s the application.ex entry:

children = [
      {Tangara.Cache, []},
      # Start the Ecto repository
      Tangara.Repo,
      # Start the Telemetry supervisor
      TangaraWeb.Telemetry,
      # Start the PubSub system
      {Phoenix.PubSub, name: Tangara.PubSub},
      # Start the Endpoint (http/https)
      TangaraWeb.Endpoint
      # Start a worker by calling: Tangara.Worker.start_link(arg)
      # {Tangara.Worker, arg}
    ]

I’ve tried all sorts of things here, without the {},calling start_link directly there.

The app start: iex -S mix phx.server

I see my IO.puts, yet if I do

iex> Tangara.Cache.get("test")

I’m getting this:

** (exit) exited in: GenServer.call(Tangara.Cache, {:get, "test"}, 5000)
    ** (EXIT) no process: the process is not alive or there's no process currently associated with the given name, possibly because its application isn't started
    (elixir 1.12.3) lib/gen_server.ex:1014: GenServer.call/3
    (tangara 0.1.0) lib/tangara/cache.ex:14: Tangara.Cache.get/1

Hopefully someone can points me to what I missed, the concept of GenServer / supervisor are all clear, yet I find myself in a situation where I’m stuck.

Thanks for your time,
Dominic

Since you are calling the genserver process by name Tangara.Cache and not its pid, you need to register the pid with that name.

For example:

GenServer.start_link(Tangara.Cache, [], name: Tangara.Cache)
1 Like

Something to keep in mind as you’ve said you’re looking for a simple cache implementation. GenServers process messages sequentially not concurrently.

Thanks so much for this :wave: