5

I try to cast message to a gen_server:

 gen_server:cast({global, ID}, {watchers}).

The handler is:

handle_cast({watchers}, State) ->
    case State#table_state.watchers of
    [] ->
        {reply, no_watchers, State};
    _ ->
        {reply, State#table_state.watchers, State}
    end;

But when I execute gen_server:cast the gen_server terminates with error:

=ERROR REPORT==== 29-Apr-2011::18:26:07 ===
** Generic server 1 terminating 
** Last message in was {'$gen_cast',{watchers}}
** When Server state == {table_state,1,"1",11,[]}
** Reason for termination == 
** {bad_return_value,{reply, no_watchers, {table_state,3,"3",11,[]}}}

Why do I get bad_return_value?

Peer Stritzinger
  • 8,232
  • 2
  • 30
  • 43
0xAX
  • 20,957
  • 26
  • 117
  • 206
  • 3
    As a side note, you don't have to send `{watchers}` (an atom inside a tuple), it's enough to send just the `watchers` atom alone as a message. – Adam Lindberg Apr 29 '11 at 12:54

1 Answers1

13

You cannot reply using cast (see gen_server documentation). That is the whole point of casting an asynchronous message instead of using call.

In your case you want to return a reply, so use gen_server:call/2 instead.

Adam Lindberg
  • 16,447
  • 6
  • 65
  • 85
  • 5
    So `handle_cast` should return `{noreply,State}`. Use `gen_server:call` and `handle_call` for a synchronous call which returns a value. – rvirding Apr 29 '11 at 15:12