Erlang中的异常处理继续执行

时间:2015-05-14 12:28:08

标签: exception error-handling exception-handling erlang ejabberd

我要做的是mochijson2:decode(Ccode)生成任何异常或错误,程序执行不应该停止并且案例分支{error,Reason}应该被执行。

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

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来说是新手。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分: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,

答案 1 :(得分: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