Created
March 24, 2016 19:25
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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