如何捕捉 GenServer 终止 Elixir

how to catch GenServer termination Elixir

我有一个带有基本设置的 DynamicSupervisor,我正在启动一个 child GenServer as

Supervisor.start_child(Recording.WorkerStarter, %{
  id: String.to_atom(detailed_camera.name),
  camera: detailed_camera,
  sleep: detailed_camera.sleep
})

并将其终止为

name
|> Process.whereis()
|> case do
  nil -> :not_found
  pid -> DynamicSupervisor.terminate_child(__MODULE__, pid)
end

我想捕捉它的终止,因为当我终止这个 child 时,我想记录一些东西。

我已经在 Recording.WorkerStarter 中测试了 terminate/2 但它不会被调用。

我已经试过了handle_info({:DOWN, ref, :process, _, _}, state)没用。

我怎样才能赶上 Recording.WorkerStarter 终止?

更新:

这是我的工人

defmodule Recording.WorkerStarter do
  use GenServer

  require Logger

  def start_link(opts) do
    IO.inspect("Started Recording.WorkerStarter")
    {id, opts} = Map.pop!(opts, :id)
    GenServer.start_link(__MODULE__, opts, name: id)
  end

  def init(state) do
    schedule_fetch_call(state.sleep)
    {:ok, state}
  end

我假设你 return :stop 来自 init/1 回调。 GenServer.terminate/2 上的文档指出:

terminate/2 is called if a callback (except init/1) [...]

也就是说,您可能会经历 GenServer.handle_continue/2 and return :stop from there, or trap exists from the calling process with Process.flag(:trap_exit, true)