Exceptional v2.1.3 Exceptional.Safe View Source

Convert a function that may raise into one that returns an exception struct

Link to this section Summary

Functions

Create a version of a function that does not raise exception. When called, it will return the exception struct instead of raising it. All other behaviour is normal

Create a version of a function that does not raise exception. It will return the exception struct instead

Link to this section Functions

Link to this function

lower(dangerous_fun, dynamic) View Source

Link to this function

safe(dangerous) View Source
safe((... -> any())) :: (... -> any())

Create a version of a function that does not raise exception. When called, it will return the exception struct instead of raising it. All other behaviour is normal.

The returned anonymous function will have the same arity as the wrapped one. 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
Link to this function

safe(dangerous, atom) View Source
safe((... -> any()), :dynamic) :: (... -> any())

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 (exactly 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