Erlang Error Handling when input argument is wrong format

Jesper Louis Andersen jesper.louis.andersen@REDACTED
Wed Mar 4 19:47:13 CET 2020


I like this solution as well.

The alternative is something like

my_fun(Arg) when is_string(Arg) ->
  do_something;
my_fun(A) when is_atom(A) ->
  my_fun(atom_to_list(A)).

which coerces the atom to a string. But in my experience, this should be
avoided unless the interface really demands that variance. It is better to
crash the code and fix it in the caller rather than trying to coerce in the
callee. Generally, if you are only accepting a small set of possible erlang
terms (i.e., strings), then your code is more robust against sending wrong
values. If you coerce/canonicalize terms, you run the risk of converting
some value which shouldn't have been and you are now running a program
where some data is undesired.

The key is that `my_fun(atom_input)` is a bug in the program. It should be
fixed by a programmer, and not saved by the system in an attempt to
continue at all cost.

On Wed, Mar 4, 2020 at 9:41 AM WW <kingwang98@REDACTED> wrote:

> Hi I have a question about the error handling in erlang when input
> argument is in wrong format.
>
> example
>
> spec my_fun(Arg:String()) -> term().
>
> In case someone calling my_fun( atom_input), how to handle the error ?
>
> my solution:
>
> my_fun(Arg) when is_string(Arg) ->
>     do_something.
>
> With the guards  the function will only take string(), when input is not a
> string the interface will generate run_time error   {error, function_fault}
>
>
> My question: Is my solution good enough ?  Any bettter way to handle the
> wrong input ?
>
>
> Best Regards W.W.(KingWang)
>


-- 
J.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20200304/9f619789/attachment.htm>


More information about the erlang-questions mailing list