0

我想要做的是mochijson2:decode(Ccode)生成任何异常或错误,程序执行不应该停止并且应该执行case branch {error,Reason}。Erlang中的异常处理继续执行

但是,当我试图让它实现时,它会在第一行生成错误,而检查并且代码不会继续执行下面的行。

SCustomid = case mochijson2:decode(Ccode) of 
    {struct, JsonDataa} -> 
     {struct, JsonData} = mochijson2:decode(Ccode), 
     Mvalll = proplists:get_value(<<"customid">>, JsonData), 
     Pcustomid = erlang:binary_to_list(Mvalll), 
     "'" ++ Pcustomid ++ "'"; 
    {error, Reason} -> escape_str(LServer, Msg#archive_message.customid) 


end, 

你可以建议,如果我需要使用Try Catch。我对Ejabberd有点经验,但对Erlang来说是新手。任何帮助表示赞赏。

回答

1

似乎是mochijson2:decode/1中发生异常的原因。该函数不会将错误作为元组返回,而是会导致进程崩溃。没有足够的信息来说明究竟是什么原因。不过我猜想Ccode的数据格式可能是错误的。您可以使用try ... catch语句处理异常:

SCustomid = try 
    case mochijson2:decode(Ccode) of 
    {struct, JsonDataa} -> 
     {struct, JsonData} = mochijson2:decode(Ccode), 
     Mvalll = proplists:get_value(<<"customid">>, JsonData), 
     Pcustomid = erlang:binary_to_list(Mvalll), 
     "'" ++ Pcustomid ++ "'"; 
    {error, Reason} -> 
     escape_str(LServer, Msg#archive_message.customid) 
    end 
catch 
    What:Reason -> 
    escape_str(LServer, Msg#archive_message.customid) 
end, 

或者只是catch

SCustomid = case catch(mochijson2:decode(Ccode)) of 
    {struct, JsonDataa} -> 
     {struct, JsonData} = mochijson2:decode(Ccode), 
     Mvalll = proplists:get_value(<<"customid">>, JsonData), 
     Pcustomid = erlang:binary_to_list(Mvalll), 
     "'" ++ Pcustomid ++ "'"; 
    {error, Reason} -> 
    escape_str(LServer, Msg#archive_message.customid); 
    {What, Reason} -> 
    escape_str(LServer, Msg#archive_message.customid) 
end, 
+0

作品完美 –

1

您可以使用此:

SCustomid = try 
        {struct, JsonData} = mochijson2:decode(Ccode), 
        Mvalll = proplists:get_value(<<"customid">>, JsonData), 
        Pcustomid = erlang:binary_to_list(Mvalll), 
        "'" ++ Pcustomid ++ "'" 
       catch _:_ -> escape_str(LServer, Msg#archive_message.customid) 
       end 
+0

完美。 –