我试图在牛仔 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,{{[{<<"register">>,<<"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">>,undefined,3000,<<"/websocket/">>,undefined,<<>>,undefined,[],[{<<"升级">>,<<"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, 像 Gecko) Chrome/30.0.1599.114 Safari/537.36">>}],[{<<"sec-websocket-extensions">>,[{<<"x-webkit-deflate-frame">>, []}]},{<<"升级">>,[<<"websocket">>]},{<<"连接">>,[<<"升级">>]}],未定义,[{websocket_compress,false},{websocket_version,13}],等待,未定义,<<>>,false,完成,[],< <>>,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}]}]}
那么我该怎么做呢?