liveBook · Manning

Exit trapping

As explained in Elixir in Action, Third Edition

Exit trapping is a process behavior in which linked-process termination signals are converted into messages instead of terminating the receiving process.

Process links propagate abnormal termination across process boundaries. Exit trapping changes that behavior: instead of terminating when a linked process crashes, the receiving process gets an exit notification in its message queue. section 8.2.1

Use exit trapping when a process must observe linked-process termination and decide what to do:

  • Call Process.flag(:trap_exit, true) in the receiving process. section 8.2.1
  • Receive the resulting {:EXIT, from_pid, exit_reason} message. section 8.2.1
  • Inspect the originating PID and termination reason, then react to the failure or remove associated state. section 8.2.1 section 10.3.4
  • Set the trap in a GenServer init/1 callback when graceful termination must invoke terminate/2 for cleanup. section 9.1.6

Detecting a linked crash

A trapping process links to a worker that raises an exception, then receives a message such as {:EXIT, pid, {%RuntimeError{message: "Something went wrong"}, stacktrace}} instead of crashing itself. section 8.2.1

iex(1)> spawn(fn ->
          Process.flag(:trap_exit, true)                        #1
 
          spawn_link(fn -> raise("Something went wrong") end)   #2
 
          receive do                                            #3
            msg -> IO.inspect(msg)                              #3
          end                                                   #3
        end)

Runnable Elixir example showing trap setup, linked-process failure, and message reception. section 8.2.1

How Elixir in Action, Third Edition covers it

How deep it goes
Defines the flag, notification tuple, and handling pattern, then applies them to GenServer shutdown and registry maintenance.
Examples
Uses a crashing linked worker, a received EXIT tuple, graceful GenServer termination, and registry deregistration.
What it assumes
Assumes process links and abnormal termination, while establishing how isolation changes when linked processes propagate exits.
What you can do after
Diagnose/debug with it by receiving linked-process failures and reacting to their PIDs and termination reasons.
How it connects
Connects process links with monitors, supervisors, GenServer callbacks, and ETS-backed process registries.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.