Elixir: Integer.parse/2 raises FunctionClauseError on count_digits/2 when given nil

Created on 24 Jul 2018  路  4Comments  路  Source: elixir-lang/elixir

Current behavior

Integer.parse(nil)

** (FunctionClauseError) no function clause matching in Integer.count_digits/2

Expected behavior

Return :error so we can pattern match on it instead of crashing.

All 4 comments

Passing nil to it is violating the contract, so raising is fine I think.

Is there a better way to parse to an integer then? String.to_integer/1 raises when given nil as well. I could pattern match the nil out ahead of time but in my use case that isn't very DRY and it would feel better to get :error from the parser.

@CaldwellYSR you should check for nil then. Create a function called parse_integer_or_nil that handles it for you.

The :error tuple is only about error in parsing for valid values. For example, if I pass an integer to File.read, I want it to fail, because that's a logical error. I don't want it to say badarg.

@CaldwellYSR For note, you really should be using dialyzer (like via the Dialyxir plugin on hex.pm makes it super easy) as it would have caught such typing issues unless your specs are incorrect yourself. It is highly recommended to use.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ericmj picture ericmj  路  3Comments

sashaafm picture sashaafm  路  3Comments

GianFF picture GianFF  路  3Comments

cmeiklejohn picture cmeiklejohn  路  3Comments

shadowfacts picture shadowfacts  路  3Comments