Concurrent Error Handling
Concurrent Error Handling with Task
In the last lesson, you chained validations with the with statement and, earlier, you used try/rescue to normalize exceptions into {:ok, value} or {:error, reason}. Today, you will combine those ideas with concurrency. You will run multiple operations at the same time with Task and collect their results safely, handling timeouts and crashes without taking down your process.
Isolating Work and Normalizing Failures
We start by defining the work and wrapping it so failures become {:error, reason} tuples. This keeps results consistent across concurrent tasks.
What it does:
fetch_data/1simulates three sources. Two return{:ok, ...}, one raises, and unknown inputs return{:error, ...}.safe_fetch/1rescues exceptions and converts them to{:error, message}. This prevents a crashing task from propagating an exit to the caller and keeps a uniform result shape.
Notes:
- Converting exceptions to tuples makes downstream orchestration simple and predictable.
- You could allow tasks to crash and handle exits, but normalizing here avoids surprises and reduces coupling.
Running Tasks Concurrently and Handling Timeouts and Crashes
Next, you spawn tasks, wait for results with a timeout, and handle all outcomes in one place.
What it does:
Task.asyncspawns three concurrent tasks that callsafe_fetch/1. Each task runs independently.Task.yield(task, 5000)waits up to 5 seconds for a result:{:ok, result}contains the exact return fromsafe_fetch/1(either{:ok, ...}or{:error, ...}).nilmeans the task did not finish in time;Task.shutdownthen tries to stop it cleanly.{:exit, ...}indicates the task terminated; both shapes are matched for robustness.
- You collect a list of final, uniform results and print them.
