Ошибка при возврате данных boss_db через веб-сокет в чикагском боссе

Я пытаюсь вернуть данные, которые я получаю с помощью boss_db через соединение через веб-сокет. В этом примере я хочу вернуть вопросы, которые я получаю, вы можете видеть, что журналы распечатывают вопрос, однако есть некоторая ошибка, которая вызывает завершение по причине: плохое возвращаемое значение: ok.

Ниже мой код и ошибка:

websocket/fan_games_game_websocket.erl

-module(fan_games_game_websocket, [Req, SessionId]).

-behaviour(boss_service_handler).

-record(state,{users}).

%% API
-export([
  init/0, 
  handle_incoming/4, 
  handle_join/3,
  handle_broadcast/2,
  handle_close/4, 
  handle_info/2,
  terminate/2
]).

init() ->
  io:format("~p (~p) starting...~n", [?MODULE, self()]),
  %timer:send_interval(1000, ping),
  {ok, #state{users=dict:new()}}.

handle_join(ServiceName, WebSocketId, State) ->
    error_logger:info_msg("~p ~p ~p", [ServiceName, WebSocketId, SessionId]),
    #state{users=Users} = State,
    {noreply, #state{users=dict:store(WebSocketId, SessionId, Users)}}.

handle_close(Reason, ServiceName, WebSocketId, State) ->
    #state{users=Users} = State,
    io:format("ServiceName ~p, WebSocketId ~p, SessiondId ~p, close for Reason ~p~n",
              [ServiceName, WebSocketId, SessionId, Reason]),
    {noreply, #state{users=dict:erase(WebSocketId, Users)}}.

handle_broadcast(Message, State) ->
  io:format("Broadcast Message ~p~n",[Message]),
  {noreply, State}.

handle_incoming(_ServiceName, WebSocketId, Message, State) ->
    error_logger:info_msg(Message),
    Questions = boss_db:find(question, []),
    error_logger:info_msg("~p~n", [Questions]),
    WebSocketId ! {text, list_to_binary(Questions)},
    {noreply, State}.

handle_info(state, State) ->
    #state{users=Users} = State,
  error_logger:info_msg("state:~p~n", [Users]),
  {noreply, State};

handle_info(ping, State) ->
  error_logger:info_msg("pong:~p~n", [now()]),
  {noreply, State};

handle_info(tic_tac, State) ->
    #state{users=Users} = State,
      Fun = fun(X) when is_pid(X)-> X ! {text, "tic tac"} end,
      All = dict:fetch_keys(Users),
      [Fun(E) || E <- All],
  {noreply, State};

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

terminate(_Reason, _State) ->
  ok.


question.erl
-module(question, [Id, GameId, Text]).
-has({answers, many}).
-belongs_to(game).

Обновлять

Вот мои обновленные журналы с вашими предложениями:

Вот журналы из примера запроса, отправляющего "a"

11:14:25.401 [info] a
fan_games_game_websocket (<0.299.0>) starting...
11:14:25.401 [info] [{question,"question-2","game-2","Who will have the most rushing yards in the first quarter?"}]

11:14:25.402 [error] ** Boss Service Handler fan_games_game_websocket terminating in handle_incoming/4
   for the reason error:badarg
ServiceUrl: "/websocket/game"
WebSocketId: <0.285.0>
SessionId  : undefined
Message    : <<"a">>
State    : {state,{dict,0,16,16,8,80,48,{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},{{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]}}}}
** Stacktrace: [{erlang,list_to_binary,[[{question,"question-2","game-2","Who will have the most rushing yards in the first quarter?"}]],[]},{fan_games_game_websocket,handle_incoming,5,[{file,"/Users/blanecordes/Documents/Code/erlang/fan_game/fan_games/src/websocket/fan_games_game_websocket.erl"},{line,42}]},{boss_service_worker,handle_cast,2,[{file,"src/boss/boss_service_worker.erl"},{line,173}]},{gen_server,handle_msg,5,[{file,"gen_server.erl"},{line,604}]},{proc_lib,init_p_do_apply,3,[{file,"proc_lib.erl"},{line,239}]}]


11:14:25.402 [error] gen_server fan_games_game_websocket terminated with reason: bad return value: ok
11:14:25.402 [error] CRASH REPORT Process <0.297.0> with 0 neighbours exited with reason: bad return value: ok in gen_server:terminate/6 line 744
11:14:25.402 [error] Supervisor {global,boss_service_sup} had child fan_games_game_websocket started with boss_service_worker:start_link(fan_games_game_websocket, <<"/websocket/game">>) at <0.297.0> exit with reason bad return value: ok in context child_terminated

person BC00    schedule 26.11.2014    source источник
comment
Стив, наверное, прав. Я также рекомендую изменить error_logger:info_msg(Questions) на error_logger:info_msg("~p~n", [Questions]), что предотвратит ОШИБКУ ФОРМАТИРОВАНИЯ во второй строке вывода.   -  person tkowal    schedule 27.11.2014
comment
@tkoval спасибо, похоже, это решило ошибку при регистрации   -  person BC00    schedule 28.11.2014


Ответы (1)


Я считаю, что проблема исходит от линии

WebSocketId ! {text, <<Questions>>},

в handle_incoming/4, потому что <<Questions>> не является правильным двоичным кодом. Попробуйте изменить его на это:

WebSocketId ! {text, list_to_binary(Questions)},

вместо.

person Steve Vinoski    schedule 26.11.2014
comment
Я вижу список двоичных ошибок после вашего изменения, я обновил свой код выше, чтобы отразить текущее состояние, большое спасибо за помощь мне в этом - person BC00; 28.11.2014
comment
Если вы видите ошибку из list_to_binary/1, то Questions явно не является списком. Судя по вашим журналам, это может быть запись #questions{}? Если это так, либо отправьте в процесс WebSocketId только соответствующие текстовые поля записи, либо, если хотите, отправьте все значение Questions как есть. Я не знаю, что процесс WebSocketId делает с сообщением {text, ...}, поэтому я не могу точно сказать вам, что делать. - person Steve Vinoski; 28.11.2014