Skip to content

Instantly share code, notes, and snippets.

@gamache
Created March 24, 2016 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gamache/fd6be7412e60484a8456 to your computer and use it in GitHub Desktop.
Save gamache/fd6be7412e60484a8456 to your computer and use it in GitHub Desktop.
SafeTask proof of concept: make a Task's raises, throws, and exits happen locally
defmodule SafeTask do
def async(func) do
safe_func = fn ->
try do
{:ok, func.()}
rescue
e -> {:error, e}
catch
:exit, x -> {:exit, x}
t -> {:throw, t}
end
end
Task.async(safe_func)
end
def await!(safe_task, timeout \\ 5000) do
case await(safe_task, timeout) do
{:ok, val} -> val
{:error, e} -> raise e
{:timeout, e} -> raise e
{:throw, t} -> throw t
{:exit, x} -> exit x
_ -> raise "SafeTask error: this is unpossible"
end
end
def await(safe_task, timeout \\ 5000) do
try do
Task.await(safe_task, timeout)
rescue
e -> {:timeout, e}
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment