Skip to content

Instantly share code, notes, and snippets.

@ahmadferdous
Created August 28, 2017 20:19
Show Gist options
  • Select an option

  • Save ahmadferdous/a5949e47b604dfda564b10c9461985df to your computer and use it in GitHub Desktop.

Select an option

Save ahmadferdous/a5949e47b604dfda564b10c9461985df to your computer and use it in GitHub Desktop.
Elixir example of trapping exit
defmodule A do
def start_link do
GenServer.start_link(__MODULE__, :ok, name: :A)
end
def fun(fun_loving_person) do
GenServer.call(fun_loving_person, :have_fun)
end
def init(:ok) do
{:ok, %{}}
end
def handle_call(:have_fun, _from, state) do
######################### Raise an error that will kill process :A
raise "TooMuchFun"
#########################
{:reply, :ok, state}
end
end
defmodule B do
def start_link do
GenServer.start_link(__MODULE__, :ok, name: :B)
end
def spread_fun(fun_seeker) do
GenServer.call(:B, {:spread_fun, fun_seeker})
end
def init(:ok) do
{:ok, %{}}
end
def handle_call({:spread_fun, fun_seeker}, _from, state) do
######################### Monitor
Process.monitor(:A)
#########################
result = A.fun(fun_seeker)
{:reply, result, state}
rescue
_ -> IO.puts "Too much fun rescued"
{:reply, :error, state}
end
######################### Receive :DOWN message because I monitor A
def handle_info({:DOWN, _ref, :process, :A, _reason}, state) do
IO.puts "################# DOWN DOWN DOWN ###########"
{:noreply, state}
end
#########################
end
{:ok, a} = A.start_link
{:ok, _b} = B.start_link
result = B.spread_fun(a)
IO.puts "#{inspect result}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment