Reputation: 689
I have the following code:
try do
IO.inspect("start task")
t = Task.async(fn -> Process.sleep(7000) end)
IO.inspect("start awaiting")
Task.await(t)
rescue
e ->
IO.inspect("catch error")
IO.inspect(e)
after
IO.inspect("after")
end
IO.inspect("success ending")
That will print:
"start task"
"start awaiting"
"after"
00:00:03.510 [info] Application my_app exited: exited in: MyApp.Application.start(:normal, [])
** (EXIT) exited in: Task.await(%Task{owner: #PID<0.497.0>, pid: #PID<0.498.0>, ref: #Reference<0.3923892342.570949633.190577>}, 5000)
** (EXIT) time out
So await crashes my caller process, and I can't rescue the error, by somehow the "after" block is used. I don't understand how I can protect my caller process from a task timeout error.
Upvotes: 4
Views: 2573
Reputation: 10061
You are going to want to use try/catch
in this particular instance.
try do
IO.inspect("start task")
t = Task.async(fn -> Process.sleep(7000) end)
IO.inspect("start awaiting")
Task.await(t)
catch
:exit, _ -> IO.puts "caught exit"
after
IO.inspect("after")
end
IO.inspect("success ending")
"start task"
"start awaiting"
caught exit
"after"
"success ending"
The differences between the two can be found in various places. This question may be a good start.
Upvotes: 11