Skip to content

Instantly share code, notes, and snippets.

@slashdotdash
Created May 28, 2020 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slashdotdash/c181afb66414e1b6aa8472bf76342a26 to your computer and use it in GitHub Desktop.
Save slashdotdash/c181afb66414e1b6aa8472bf76342a26 to your computer and use it in GitHub Desktop.
Elixir GenServer with a `handle_info/2` callback will crash when receiving an unexpected message

Elixir GenServer with a handle_info/2 callback will crash when receiving an unexpected message

Define a GenServer with a handle_info callback function:

defmodule Echo do
  use GenServer

  def start_link(reply_to) do
    GenServer.start_link(__MODULE__, reply_to)
  end

  @impl GenServer
  def init(reply_to) do
    {:ok, reply_to}
  end

  @impl GenServer
  def handle_info(:ping, reply_to) do
    send(reply_to, :pong)
    
    {:noreply, reply_to}
  end
end

Start the process and send it an expected message:

 {:ok, pid} = Echo.start_link(self())

 send(pid, :ping)

 flush()

Sending an unexpected message will crash the GenServer process.

iex> send(pid, :unexpected)
iex> 15:50:36.859 [error] GenServer #PID<0.133.0> terminating
** (FunctionClauseError) no function clause matching in Echo.handle_info/2
    iex:14: Echo.handle_info(:unexpected, #PID<0.108.0>)
    (stdlib) gen_server.erl:637: :gen_server.try_dispatch/4
    (stdlib) gen_server.erl:711: :gen_server.handle_msg/6
    (stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3
Last message: :unexpected
State: #PID<0.108.0>
** (EXIT from #PID<0.108.0>) shell process exited with reason: an exception was raised:
    ** (FunctionClauseError) no function clause matching in Echo.handle_info/2
        iex:14: Echo.handle_info(:unexpected, #PID<0.108.0>)
        (stdlib) gen_server.erl:637: :gen_server.try_dispatch/4
        (stdlib) gen_server.erl:711: :gen_server.handle_msg/6
        (stdlib) proc_lib.erl:249: :proc_lib.init_p_do_apply/3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment