Hi
I’ve seen this Approach 2 https://semaphoreci.com/blog/2016/11/24/how-to-capture-all-errors-returned-by-a-function-call-in-elixir.html, but I cannot work through adapting it for a function that accepts arguments.
I think it needs to pipe into spawn_monitor/3
rather than spawn_monitor/1
.
Here’s the code for completeness. My only attempt doesn’t use the capture function or the wrapper. Just calls spawn_monitor( Module, :function, [args])
but then I cannot find a way of getting at the return value because, I guess, there’s no wrapper.
Thanks,
def capture(callback, timeout_ms) do
{pid, monitor} = callback |> propagate_return_value_wrapper |> spawn_monitor
receive do
{:DOWN, ^monitor, :process, ^pid, :normal} ->
receive do
{__MODULE__, :response, response} -> {:ok, response}
end
{:DOWN, ^monitor, :process, ^pid, reason} ->
Logger.error "#{__MODULE__}: Error in handled function: #{inspect reason}";
{:error, reason}
after timeout_ms ->
pid |> Process.exit(:kill)
Logger.error "#{__MODULE__}: Timeout..."
{:error, {:timeout, timeout_ms}}
end
end
defp propagate_return_value_wrapper(callback) do
caller_pid = self
fn-> caller_pid |> send( {__MODULE__, :response, callback.()}) end
end