OnCrash (OnCrash v0.1.0) View Source

Convinence module to wrap a monitor and call a function when a process ends. Useful to setp cleanup tasks on process shutdown.

worker = spawn(fn ->
  OnCrash.call(fn -> cleanup() end)
  do_the_work()
end)

OnCrash is always called when the process finished. So it will aso run the callback when the process ends with a :normal exit reason. To have exit reason specific code a fun with a reason parameter can be specified:

worker = spawn(fn ->
  OnCrash.call(fn reason ->
    if reason != :normal do
      IO.puts("Worker died with reason #{inspect(reason)}")
      cleanup()
    end
  end)
  do_the_work()
end)

Link to this section Summary

Functions

Registers the given fun as callback to be executed once the process exits. pid is provided it binds to the given process. Otherwise it binds to the current executing process.

Link to this section Functions

Link to this function

call(pid \\ self(), fun)

View Source

Specs

call(pid() | nil, (() -> any()) | (reason -> any())) :: true when reason: any()

Registers the given fun as callback to be executed once the process exits. pid is provided it binds to the given process. Otherwise it binds to the current executing process.

  worker = spawn(fn ->
    OnCrash.call(fn -> cleanup() end)
    do_the_work()
  end)

And to differentiate

  worker = spawn(fn ->
    OnCrash.call(fn reason ->
      case reason do
        # On raise "oh_no!"
        {%RuntimeError{message: "oh_no!"}, _backtrace} -> you_code_here()
        # On throw(:oh_no!)
        {{:nocatch, :oh_no!}, _backtrace} -> you_code_here()
        # On exit(:oh_no!)
        :oh_no! -> you_code_here()
      end
      cleanup()
    end)
    do_the_work()
  end)