t56k
t56k

Reputation: 7011

Elixir: guarding against argument errors

If I have a pipeline like this:

"1" |> String.to_integer

How can I guard against it if the string is empty (not nil)?

"" |> String.to_integer
** (ArgumentError) argument error
:erlang.binary_to_integer("")

Upvotes: 2

Views: 530

Answers (2)

PatNowak
PatNowak

Reputation: 5812

Everything depends on the context. For instance you can use default value and use it in your private function.

defp convert_to_integer(my_string \\ 0) # if 0 is appropriate default value
  String.to_integer(my_string)
end

Of course there's a better way - Integer.parse, which returns valid tuple if everything's fine and :error if there's something wrong. Just combine it with cond or case.

defp convert_to_integer(my_string)
  result = Integer.parse(my_string)

  case result do
    {number, _} -> number
    :error -> "it didn't work" # or anything      
  end
end

Upvotes: 4

TheAnh
TheAnh

Reputation: 2813

Try pattern matching to guard this:

def to_integer(string) when byte_size(string) == 0 do
  # do_something_with_empty_string
  IO.puts "empty"
end

def to_integer(string) do
  # handle your case here
  String.to_integer(string)
end

Iex:

iex(9)> Test.to_integer("")
empty
:ok
iex(10)> Test.to_integer("2")
2

Upvotes: 1

Related Questions