Exceptional v1.3.0 Exceptional.Safe
Convert a function that may raise
into one that returns an exception struct
Summary
Functions
Create a version of a function that does not raise exception. When called, it will return the exception struct instead of raising exceptions. All other behaviour is normal
Create a version of a function that does not raise exception. It will return the exception struct instead
Functions
Create a version of a function that does not raise exception. When called, it will return the exception struct instead of raising exceptions. All other behaviour is normal.
The returned anonymous function will have the same arity as the wrapped function. For technical reasons, the maximum arity is 9 (like most sane functions).
If you need a higher arity, please use the :dynamic
option in safe/2
.
iex> toothless = safe(&Enum.fetch!/2)
...> [1,2,3] |> toothless.(1)
2
iex> toothless = safe(&Enum.fetch!/2)
...> [1,2,3] |> toothless.(999)
%Enum.OutOfBoundsError{message: "out of bounds error"}
It also works on functions that wouldn’t normally raise
iex> same = safe(&Enum.fetch/2)
...> [1,2,3] |> same.(1)
{:ok, 2}
iex> same = safe(&Enum.fetch/2)
...> [1,2,3] |> same.(999)
:error
Create a version of a function that does not raise exception. It will return the exception struct instead.
With the :dynamic
option passed, it takes a list of arguments (like Kernel.apply
)
iex> toothless = safe(&Enum.fetch!/2, :dynamic)
...> toothless.([[1,2,3], 1])
2
iex> toothless = safe(&Enum.fetch!/2, :dynamic)
...> toothless.([[1,2,3], 999])
%Enum.OutOfBoundsError{message: "out of bounds error"}
It also works on functions that wouldn’t normally raise
iex> same = safe(&Enum.fetch/2, :dynamic)
...> same.([[1,2,3], 1])
{:ok, 2}
iex> same = safe(&Enum.fetch/2, :dynamic)
...> same.([[1,2,3], 999])
:error