[erlang-questions] using guards in gen_server

Ulf Wiger <>
Sun Aug 29 21:33:56 CEST 2010

On 29/08/2010 11:20, Zvi wrote:
> Hi,
> When writing gen_server, do you put validation guards in API functions
> or in handle_call / cast or in both ? What's the convention?

A convention I use, for cases where I really can't know
until in the handle_call whether the input is ok, is to
e.g. reply 'badarg' and handle it in a wrapper around


call(Req) ->
     call(Req, l).

call(Req, l) ->
     chk_reply(gen_server:call(?MODULE, Req), Req);
call(Req, g) ->
     chk_reply(gproc_dist:leader_call(Req), Req).

chk_reply(Reply, Req) ->
     case Reply of
         badarg -> erlang:error(badarg, Req);
         Reply  -> Reply

A slight disadvantage is that the error is reported as
happening in chk_reply/2 rather than in the API function.
This could be fixed e.g. by adding some ugly macros.

The server side might then look like:


handle_call({reg, {_T,l,_} = Key, Val}, {Pid,_}, S) ->
     case try_insert_reg(Key, Val, Pid) of
         true ->
             {reply, true, S};
         false ->
             {reply, badarg, S}

Ulf W
Ulf Wiger
CTO, Erlang Solutions Ltd, formerly Erlang Training & Consulting Ltd

More information about the erlang-questions mailing list