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

Jachym Holecek freza@REDACTED
Fri May 13 21:59:20 CEST 2011


# Ciprian Dorin Craciun 2011-05-13:
>     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. [...]
> 
>     I think of three possibilities:
>     * reply back with an error:

Yep, this is what I do:

  handle_call(_, _, State) ->
      {reply, {error, bad_request}, State}.

  handle_info(_, State) ->
      {noreply, State}.

It's similar with gen_fsm & custom processes.

>     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;

It also helps forward-compatibility in presence of hot code upgrades.

>     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?

Depends on how tightly they're bound together. Linking them means "one
can't live without the other even for a second", monitoring means "one
is vaguely interested if the other is still alive" (often to clean up
some mess when the other dies), fail on call means "ok, I need you to
handle my request now, but generally I don't really care about you".

The last option is by far the most common, the other two are employed
tactically in cases where it matters.

HTH,
	-- Jachym



More information about the erlang-questions mailing list