adobroskok
Trapping exit reason in Supervisor
I need help with seem to be a trivial task. My application root is Supervisor and it starts couple of GenServer based workers. I am trying to find a way to catch worker termination reason in my Supervisor, but for some reason I can’t find a way to do this. After reading through Hexdocs I figured out that with GenServer I can define terminate callback in GenServer, but it is not always guaranteed to be called. As supervisor is responsible for restarting terminated children I based on exit reason (:normal, :shutdown,…) I assume there should be a way to catch it.
Thanks in advance for your help.
Most Liked
voltone
Supervisors are critical to the application’s reliability, so it is recommended to always use OTP’s standard (proven, simple, robust) supervisors rather than roll your own.
If some part of your application needs to be notified when processes terminate, add a GenServer that uses Process.monitor/1 to track other processes. This is orthogonal to the supervision hierarchy and therefore any issues in your monitoring code will not impact supervision.
ndac_todoroki
I am pretty late here, but I’m afraid one can not overwrite Supervisors handle_info/2, as well as handle_call and handle_cast, because while Supervisor does not define those callbacks.
defmodule Sup do
use Supervisor
def handle_info(any, state) do
IO.inspect any
end
end
# try messaging
send(sup_pid, :hello)
Trying the above does not work, it will say something like
01:52:12.737 [error] Supervisor received unexpected message: :hello
The handle_info handle_call the Supervisor can receive seems to be defined here, and Elixir is just calling that inside def which_children, do: ....
idi527
Maybe you can overwrite handle_info/2 in your supervisor module?
require Logger
def handle_info({:EXIT, pid, reason}, state) do
Logger.info("A child process died: #{reason}")
case restart_child(pid, reason, state) do # it's a private function ... that's a problem
{:ok, state} ->
{:noreply, state}
{:shutdown, state} ->
{:stop, :shutdown, state}
end
end
def handle_info(msg, state) do
Logger:error("Supervisor received unexpected message: #{inspect(msg)}")
{:noreply, state}
end
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








