Skip to content

Instantly share code, notes, and snippets.

@WLSF
Created November 15, 2020 17:15
Show Gist options
  • Save WLSF/07acab85524a065843f89c53c9f570f9 to your computer and use it in GitHub Desktop.
Save WLSF/07acab85524a065843f89c53c9f570f9 to your computer and use it in GitHub Desktop.
Macro to catch errors
defmodule Report do
defmacro __using__(_opts) do
quote do
import Report
end
end
defmacro dispatch(name, do: block) do
function_name = String.to_atom(name)
IO.inspect(block)
{:with, _, params} = block
with_else =
params
|> List.last()
|> Keyword.put(:else,
quote do
error -> error
end)
params = List.replace_at(params, 1, with_else)
block =
block
|> Tuple.delete_at(2)
|> Tuple.insert_at(2, params)
IO.inspect(block)
quote do
def unquote(function_name)() do
unquote(block)
end
end
end
end
defmodule Request do
use Report
dispatch "get_level" do
with {:ok, value} <- test() do
value
end
end
defp test do
{:error, "n funfou"}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment