如何处理牛仔网络套接字处理程序中的异常



我试图在牛仔 websocket 处理程序中使用 jiffy 解析它时捕获无效的 json。如果 json 有效/无效,我想将适当的消息转发给websocket_info该消息将回复客户端。这是我的代码。

websocket_handle({text, Msg}, Req, State) ->
lager:info("Got message ~p",[Msg]),
try  jiffy:decode(Msg) of 
    {[{A,B}]}->{{[{A,B}]},Req,State};
    _->{{invalid,Msg},Req,State}
catch
    _:_->
        {{invalid,Msg},Req,State}
end;
websocket_handle(_Data, Req, State) ->
                 {ok, Req, State}.
websocket_info({[{A,B}]},Req,State) ->
               {reply,{text,jiffy:encode({registered,B})},Req,State};
websocket_info({invalid,Msg},Req,State)->
              {reply,{text,jiffy:encode({error,<<"invalid json">>})},Req,State};

这会导致运行时异常。

12:07:48.406 [错误] 牧场侦听器 http 的连接进程<0.523.0>退出原因: {{try_clause,{{[{<<"注册">>,<<"my-channel">>}]},{http_req,#Port<0.1337>,ranch_tcp,keepalive,<0.523.0>,<<"GET">>,'HTTP/1.1',{{127,0,0,1},

34869},<<"127.0.0.1">>,未定义,3000,<<"/websocket/">>,未定义,<<>>,未定义,[],[{<<"升级">>,<<"Websocket">>},{<<"connection">>,<<"Upgrade">>},{<<"host">>,<<"127.0.0.1:3000">>},{<<"origin">>,<<" http://localhost:4000 ">>},{<<"pragma">>,<<"no-cache">>},{<<"cache-control">>,<<"no-cache">>},{<<"sec-websocket-key">>,<<"ueSRxsIc4wM7KdGnyhJOhw===">>},{<<"sec-websocket-version">>,<<"13">>},{<<"sec-websocket-extensions">>,<<"x-webkit-deflate-frame">>},{<<"user-agent">>,<<"Mozilla/5.0 (X11;Linux i686 (x86_64)) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.114 Safari/537.36">>}],[{<<"sec-websocket-extensions">>,[{<<"x-webkit-deflate-frame">>,[]}]},{<<"upgrade">>,[<<"websocket">>]},{<<"connection">>,[<<"upgrade">>]}],undefined,[{websocket_compress,false},{websocket_version,13}],waiting,undefined,<<>>,false,done,[],<<>>,undefined},undefined_state}},[{cowboy_websocket,handler_call,7,[{file,"src/cowboy_websocket.erl"},{line,598}]},{cowboy_protocol,execute,4,[{file,"src/cowboy_protocol.erl"},{line,529}]}]}

那么我该怎么做呢?

回复应从websocket_handle返回:

websocket_handle({text, Msg}, Req, State) ->
    lager:info("Got message ~p", [Msg]),
    try jiffy:decode(Msg) of 
        {[{A, B}]}->
            {reply, {text, jiffy:encode({[{registered,B}]})}, Req, State};
        _ -> 
            {reply, {text, jiffy:encode({[{error,<<"invalid json">>}]})}, Req, State} 
    catch
        _:_ ->
            {reply, {text, jiffy:encode({[{error,<<"invalid json">>}]})}, Req, State};
    end;
websocket_handle(_Data, Req, State) ->
    {ok, Req, State}.
websocket_info(_Info, Req, State) ->
    {ok, Req, State}.

最新更新