...

/

Use Task.Supervisor

Use Task.Supervisor

Learn about the working of task supervisors and see what happens if there is no supervisor.

Run without a supervisor

Before we switch to EmailTaskSupervisor, let’s see what happens when an error occurs and there is no supervisor in place. We’ll simulate an error by raising an exception when we send one of our fake emails. The following changes are required in sender.ex:

Press + to interact
#file path -> sender/lib/sender.ex
def send_email("konnichiwa@world.com" = email), do:
raise "Oops, couldn't send email to #{email}!"
def send_email(email) do
Process.sleep(3000)
IO.puts("Email to #{email} sent")
{:ok, "email_sent"}
end

We use pattern matching to raise an exception only when the email address is konnichiwa@world.com.

We then add the following code to application.ex as discussed in the previous lesson:

Press + to interact
#file path -> sender/lib/sender/application.ex
children = [
{Task.Supervisor, name: Sender.EmailTaskSupervisor}
]

Let’s see the impact of this error in practice. We can click the “Run” button to run the code in the IEx shell and try these commands below.

Let’s run the built-in self/0 function.

This is the executable command:

Press + to interact
self()

Here’s the output we get:

iex(1)> self()
#PID<0.163.0>

We get a process identifier for ...