Skip to content

Make dangerous functions safe

Compare
Choose a tag to compare
@expede expede released this 18 Dec 04:25
· 19 commits to master since this release

safe/1 & safe/2 (plus pun aliases: lower/1 and lower/2 make functions that raise exceptions return those exceptions instead.

Does not catch throws, because that causes all sorts of odd behaviour (REPL errors returned as tuples or (structs if normalized), then they get piped into functions... all sorts of mess).

toothless_fetch = safe(&Enum.fetch!/2)
[1,2,3] |> toothless_fetch.(1)
#=> 2

toothless = safe(&Enum.fetch!/2)
[1,2,3] |> toothless.(999)
#=> %Enum.OutOfBoundsError{message: "out of bounds error"}

safe(&Enum.fetch!/2).([1,2,3], 999)
#=> %Enum.OutOfBoundsError{message: "out of bounds error"}