Hey there,
I’m new to Elixir and OTP and coming from an OO background, I’m still wrapping my head around Processes, Supervisors, Tasks etc.
I’m currently working on a little program that has to go through a bunch of files, read from them, parse the data and do something with it.
I’m trying to speed up this process by using Tasks and I’ve setup a TaskSupervisor which I then use to dynamically start Tasks that parse the data from the file.
It looks something like this
def do_the_thing(dir) do
for file <- File.ls!(dir) do
file_name = "#{dir}/#{file}"
File.read!(file_name)
|> Parser.parse!()
|> Enum.each(fn parsed_data ->
Task.Supervisor.start_child(MyApp.TaskSupervisor, MyTask, :run, [
parsed_data
])
end)
end
end
Now this works fine but when an error is raised and MyTask fails, I want to somehow trap the exception and log it in a file with additional metadata so I can see where it failed.
I had a try rescue block inside the MyTask.run function but I have a feeling that’s unnecessary since I’m fine with the Task failing, the ever vigilant Supervisor handles that for me just fine.
I guess my question is, what’s considered best practices when I want to catch exit reasons and log if they interest me. I tried to setup something with Process.monitor but couldn’t really figure out how to match exceptions and not :normal exits.