[erlang-questions] Best practices for handling invalid / unexpected messages

Ciprian Dorin Craciun <>
Fri May 13 20:46:51 CEST 2011


    Hello all!

    Lately I've started programming a bit more seriously in Erlang,
and after creating a few `gen_server` or `gen_fsm` components, I've
started wondering what is the best way to handle unexpected or invalid
requests / messages. (For example in `handle_call`, or `handle_info`
or state handlers.) (By invalid requests I mean those that have the
correct form (i.e. a tuple `{add, A, B}`) but invalid syntax (i.e. `A`
is an atom); by unexpected messages I mean those that fail to even
loosely match a valid pattern (i.e. `{some_unrecognized_operation, A,
B}`.)

    I think of three possibilities:
    * reply back with an error:
~~~~
handle_call (Request, _Sender, State) -> {reply, {error,
{invalid_request, Request}}, State}.
~~~~
    * exit with an error;
~~~~
handle_call (Request, _Sender, State) -> {stop, {error,
{invalid_request, Request}}, State}.
~~~~
    * don't even create a special catch-all case and just let the
process fail with `function_clause` error;

    Now each of these have advantages or disadvantages:
    * the first one is "polite" to the caller, letting him retry, but
could lead to hidden bugs if the caller doesn't check the return term;
    * the second one I think fits more the Erlang philosophy of
"let-it-crash", but could lead to state loss (i.e. an ETS table);
    * the last one I consider to be just rude as it doesn't give any
information on why it failed;

    Furthermore, let's say a process depends in his operation on
another process, should it link the dependency process, should it
monitor, or should it just fail on call?

    So I ask the other Erlang developers how do they handle these situations?

    Thanks,
    Ciprian.



More information about the erlang-questions mailing list