OnCrash - Method to attach a callback to a process exit

After having this done a couple of times in different projects I decided to make this quick helper method that creates a monitor, attaches it to the desired process and fires a fun when the process goes down.

So makes it easy as pie to attach a cleanup() function to a process:

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

That’s really all there is to it. Ah and if you’re curious about the exit reason you can have that as well:

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


https://hexdocs.pm/oncrash/OnCrash.html

Make a comment if this is helpful for you as well!

Cheers!

5 Likes